DateFormatter does not return a date for "HH: mm: ss"

Here is the code snippet:

func mapping(map: Map) { time <- (map["time"], TransformOf<Date, String>(fromJSON: { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm:ss" //dateFormatter.timeZone = TimeZone(abbreviation: "EEST") if let argument = $0 { let date = dateFormatter.date(from: argument) return dateFormatter.date(from: argument) } return nil }} 

$0 is the line with "22:12:00" . I set the "dating" to see what it returns, and this is zero. I searched for format codes here: http://waracle.net/iphone-nsdateformatter-date-formatting-table/

The code should actually work. What am I doing wrong?

EDIT : added whole function

EDIT2 : I just noticed that it works correctly on iPhone 7 iOS 10.1, but returns zero on iPod 10.1.1 (2016). This is so strange.

+13
date ios swift swift3
source share
1 answer

From the QA1480 Technical Q & A - NSDateFormatter and Internet Dates (highlighted added):

On the other hand, if you are working with fixed-format dates, you must first set something suitable for your fixed-format date locale. In most cases, the best language to choose is en_US_POSIX, a language specifically designed to produce US English results, regardless of user and system preferences.

This will prevent the date from being interpreted according to the user's regional settings:

 let dateFormatter = DateFormatter() // Set the locale first ... dateFormatter.locale = Locale(identifier: "en_US_POSIX") // ... and then the date format: dateFormatter.dateFormat = "HH:mm:ss" // ... 

See also. What is the best way to work with the NSDateFormatter "feechur" locale? ,

+24
source share

All Articles