NSDateFormatter returns nil in swift and iOS SDK 8.0

后端 未结 2 777
后悔当初
后悔当初 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:29

    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.

提交回复
热议问题