1

I found out some strange behaviour of DateFormatter on iOS 13.4.1 while 12 hour date style set in the iOS settings and now is PM.

class DateFormatterTest {
    
    static var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS Z"
        return formatter
    }()
    
    static let testDate = Date()
    
    static func printDateString() {
        
        print(dateFormatter.string(from: testDate))
    }
}

DateFormatterTest.printDateString() 
// prints 2020-08-01 15:32:58.765 +0300 when 24h date style set in the iOS 13.4.1 system
// prints 2020-08-01 3:32:58.765 +0300 when 12h date style set in the iOS 13.4.1 system (EXPECTED: same as when 24h date style set.)

Note that while testing this using Playground there is no matter which date style set on MacOS the playground always prints "2020-08-01 15:32:58.765 +0300" which is correct.

The question is how to get correct formatted date string in format "yyyy-MM-dd HH:mm:ss.SSS Z" while 12h time style set on iOS 13.4.1

I didn't test on other iOS versions, so please comment if you see (or don't see) the same behaviour on another iOS version

Dmitry
  • 2,963
  • 2
  • 21
  • 39
  • 2
    try set formatter.locale = Locale(identifier: "en_US_POSIX") – aiwiguna Aug 01 '20 at 13:13
  • @aiwiguna, you are right. Setting locale does the magic. Do you know why it doesn't work without locale? – Dmitry Aug 01 '20 at 14:09
  • see Working With Fixed Format Date Representations section https://developer.apple.com/documentation/foundation/dateformatter – aiwiguna Aug 01 '20 at 14:12
  • 1
    **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** https://developer.apple.com/library/archive/qa/qa1480/_index.html – Leo Dabus Aug 01 '20 at 15:39

1 Answers1

1

The problem is fixed. Locale needs to be set.

formatter.locale = Locale(identifier: "en_US_POSIX")
Dmitry
  • 2,963
  • 2
  • 21
  • 39