使用iOS7的Swift ISO-8601日期格式 [英] Swift ISO-8601 date formatting with iOS7

查看:150
本文介绍了使用iOS7的Swift ISO-8601日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的需要你的帮助。以下代码在Swift Playgound和任何iOS8或8.1模拟器中都可以正常工作。但是使用iOS7和7.1,NSDate对象总是设置为nil。



对象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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆