NSDateFormatter returns nil in swift and iOS SDK 8.0

后端 未结 2 782
后悔当初
后悔当初 2020-12-07 01:46

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 conver

2条回答
  •  星月不相逢
    2020-12-07 02:18

    NSDateFormatter's behaviors are heavily depends on it's locale. By default, it uses device locale. If you want consistent result from it, You should manually specify the locale. In most cases, en_US_POSIX is the best.

    The document says:

    If you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. 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. en_US_POSIX is also invariant in time (if the US, at some point in the future, changes the way it formats dates, en_US will change to reflect the new behavior, but en_US_POSIX will not), and between platforms (en_US_POSIX works the same on iPhone OS as it does on OS X, and as it does on other platforms).

    Like this:

    let dateString = "2014-06-21 14:56:00 EST"
    
    let dateFormatter = NSDateFormatter()
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
    var date: NSDate? = dateFormatter.dateFromString(dateString)
    

提交回复
热议问题