简体   繁体   中英

Swift ISO-8601 date formatting with iOS7

I really need your help guys. The following piece of code works fine in a Swift Playgound and with any iOS8 or 8.1 simulator. But with iOS7 and 7.1, the NSDate object is always set to nil.

The object dateString contains a JSON string (ISO 8601 format) like 2015-02-28T20:15:00+0100 I'm trying to convert this date string into a NSDate object with the following code :

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.ZZZ"
if let dateString = (json as NSDictionary).valueForKey("dateAndTime") as? String
{
   let dateObject = dateFormatter.dateFromString(dateString)
}

Where's my mistake ? I'm getting confused! Many thanks

The problem is with your time zone offset, your date format is not proper for that. Use the following format,

"yyyy-MM-dd'T'HH:mm:ssZZZZZ"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM