DateFormatter Bug iOS Swift with 24 Hours Format iPhone XR

extension Date {
  var _24Format: String {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = "HH:mm"
        return dateFormatter.string(from: self)
    }
}

expected result from this computed property when the time is 5:00 pm is 17:00 but this not the case in all devices especially iphone XR , iphone 6S , the result was 5:00 we take a lot of time to detect this issue because it didn't appear in our iphone 7+ test device ,we detect this issue by debug this issue on a real user device . by debugging we discover this up normal behavior we start search and try many different solutions and this solution solve it

extension Date {
  var _24Format: String {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(abbreviation: "EET")!
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = "HH:mm"
        return dateFormatter.string(from: self)
    }
}
1 Like

The hour format follows the user's device settings.

DateFormatter > Working With Fixed Format Date Representations

When working with fixed format dates, such as RFC 3339, you set the dateFormat property to specify a format string. For most fixed formats, you should also set the locale property to a POSIX locale ("en_US_POSIX"), and set the timeZone property to UTC.
For more information, see Technical Q&A QA1480 “NSDateFormatter and Internet Dates”.

Technical Q&A QA1480

On iOS, the user can override the default AM/PM versus 24-hour time setting (via Settings > General > Date & Time > 24-Hour Time), which causes NSDateFormatter to rewrite the format string you set, which can cause your time parsing to fail.

2 Likes
Terms of Service

Privacy Policy

Cookie Policy