使用iOS7的Swift ISO-8601日期格式 [英] Swift ISO-8601 date formatting with iOS7
问题描述
对象dateString包含一个JSON字符串(ISO 8601格式),如 2015-02- 28T20:15:00 + 0100
我试图将这个日期字符串转换为NSDate对象,其代码如下:
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:en_US_POSIX)
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.dateFormat = yyyy-MM-dd'T'HH:mm:ss.ZZZ
如果让dateString =(json as NSDictionary).valueForKey(dateAndTime)as? String
{
let dateObject = dateFormatter.dateFromString(dateString)
}
我的错误在哪里?我很困惑!
非常感谢
问题在于您的时区偏移,您的日期格式不适合。使用以下格式,
yyyy-MM-dd'THH:mm:ssZZZZZ
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"
这篇关于使用iOS7的Swift ISO-8601日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!