Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to NSDate with Swift 2

I'm trying to convert a string to NSDate here is my code

     let strDate = "2015-11-01T00:00:00Z" // "2015-10-06T15:42:34Z"
     let dateFormatter = NSDateFormatter()
     dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ssZ"
    print ( dateFormatter.dateFromString( strDate ) )

I keep getting nil as a result

like image 582
iOSGeek Avatar asked Oct 10 '15 19:10

iOSGeek


People also ask

How to convert string to date in Swift 4. 2?

let isoDate = "2016-04-14T10:44:00+0000" let dateFormatter = DateFormatter() dateFormatter. locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter. dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" let date = dateFormatter. date(from:isoDate)!

How to change date into string in Swift?

We start by creating a Date object. To convert the date to a string, we need to create a date formatter, an instance of the DateFormatter class. To convert the Date object to a string, we invoke the date formatter's string(from:) instance method.

What is en_US_POSIX?

In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.


1 Answers

The "T" in the format string needs to be single quoted so it will not be consider a symbol:

Swift 3.0

let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:strDate)
print("date: \(date!)")

Output:

date: 2015-11-01 00:00:00 +0000

Swift 2.x

let strDate = "2015-11-01T00:00:00Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.dateFromString(strDate)
print("date: \(date!)")

Output:

date: 2015-11-01 00:00:00 +0000

See: Date Field SymbolTable.

This includes the need to enclose ASCII letters in single quotes if they are intended to represent literal text.

like image 75
zaph Avatar answered Oct 13 '22 11:10

zaph