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
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)!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With