Swift - Convert a string to a date and then to a string in a different format

Suppose I have a simple string extracted from an array of strings (representing dates) -

var myDateString = "2015-11-25 04:31:32.0"

Now I want to convert it to a string that looks like November 25, 2015 .

For this, I assume that I need -

  • get NSDate date object from string using NSDateFormatter
  • get a string from this NSDate object using some functionality (which I could not find)

I tried this on the Playground but could not solve such a simple problem.

Here is what I tried -

Line 1| var dateFormatter = NSDateFormatter()
Line 2| dateFormatter.locale = NSLocale.currentLocale()
Line 3| dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss.A"
Line 4| let somedate = dateFormatter.dateFromString(str)
Line 5| let somedateString = dateFormatter.stringFromDate(somedate!)

In the Xcode sidebar, line 4 prints "Nov 25, 2015, 12:00 AM", but when I try to print a line from somedate, I get "2015-11-25 00:00:00.0".

I have not found a single correct explanation of NSDates anywhere.

Java parse() format() Dates.

+4
2

Swift 3.0

: , NSDate,

    let myDateString = "2016-01-01 04:31:32.0"

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.A"
    let myDate = dateFormatter.date(from: myDateString)!

    dateFormatter.dateFormat = "MMM dd, YYYY"
    let somedateString = dateFormatter.string(from: myDate)

, YYYY yyyy. , YYYY .

Apple .

YYYY. yyyy , YYYY ( " " ), ISO . yyyy YYYY , . .

+17

, . , , .A .S . (. Unicode, @MartinR)

.A -

.S -

:

let dateString = "2015-11-25 04:01:32.0"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.S"                 // Note: S is fractional second
let dateFromString = dateFormatter.dateFromString(dateString)      // "Nov 25, 2015, 4:31 AM" as NSDate

let dateFormatter2 = NSDateFormatter()
dateFormatter2.dateFormat = "MMM d, yyyy"

let stringFromDate = dateFormatter2.stringFromDate(dateFromString!) // "Nov 25, 2015" as String
+3

Source: https://habr.com/ru/post/1624570/


All Articles