NSDateFormatter在swift和iOS SDK 8.0中返回nil [英] NSDateFormatter returns nil in swift and iOS SDK 8.0

查看:98
本文介绍了NSDateFormatter在swift和iOS SDK 8.0中返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Raywenderlich提供的教程,第29章新内容测试,并遇到一个奇怪的问题。



以下是教程中将字符串转换为日期的代码:

  //将日期字符串转换为日期。 
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat =yyyy-MM-dd HH:mm:ss zzz
var date:NSDate? = dateFormatter.dateFromString(dateString)

dateString的格式为

  2014-06-21 14:56:00 EST 

但是,日期变量总是为零。



注意:在操场上播放此代码时,它可以正常工作,如图所示: / p>



我在iOS SDK 8.0中工作。这是SDK的错误吗?






更新



我正在使用iOS 8的最新iPod Touch进行测试。

解决方案

当您设置 dateFormat string您还必须将 locale 属性设置为与提供的格式兼容的属性。否则,区域设置将基于可能不兼容的设备设置。



此处提供的日期格式将与en区域设置一起使用但不起作用与许多其他人,如欧盟。这是一个例子:

  let dateString =2014-06-21 14:56:00 EST

让localeStr =eu//这将给出nil
让localeStr =us//这将成功

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:localeStr)
dateFormatter.dateFormat =yyyy-MM-dd HH:mm:ss zzz
var date:NSDate? = dateFormatter.dateFromString(dateString)

这里的问题是EST,它只存在于北美洲。在所有其他语言环境中,它是无效的时区。如果您将日期字符串更改为:

 2014-06-21 14:56:00 UTC-5

然后无论什么值 locale 设置为。


I am reading the tutorial provided by Raywenderlich, Chapter 29 What’s New with Testing, and run into a strange problem.

Following is the code in the tutorial converting a string into date:

// Convert date string to date.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
var date: NSDate? = dateFormatter.dateFromString(dateString)

The dateString is of the form

2014-06-21 14:56:00 EST

However, the date variable is always nil.

NOTE: when playing this code in the playground, it works properly, as the image shows:

I am working in iOS SDK 8.0. Is it a bug of the SDK?


Updated

I am testing using a latest iPod Touch with iOS 8.

解决方案

When you set a dateFormat string you must also set the locale property to something that is compatible with the format provided. Otherwise the locale will be based on the device settings which may not be compatible.

The date format you provided here will work with the "en" locale but it will not work with many others, such as "eu". Here's an example:

let dateString = "2014-06-21 14:56:00 EST"

let localeStr = "eu" // this will give nil
let localeStr = "us" // this will succeed

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: localeStr)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
var date: NSDate? = dateFormatter.dateFromString(dateString)

The problem here is "EST" which only exists in the north america. In all other locales it is an invalid timezone. If you change your date string to this:

"2014-06-21 14:56:00 UTC-5"

Then it the date will correctly format no matter what value locale is set to.

这篇关于NSDateFormatter在swift和iOS SDK 8.0中返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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