DateFormatter not working, If I change the TimeZone in iPhone settings

DateFormatter parses the date correctly when using the default timezone in iPhone settings. However, if I change to any custom TimeZone, DateFormatter returns nil.

Here is the code snippet

extension String{
    func toDate() -> Date?{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd-MMM-yyyy hh:mm a"
        let date = dateFormatter.date(from:self)
        return date ?? nil
    }
}

If I use the default time zone settings in iPhone Settings, it works. However, if I change the time zone to a custom one and switch to a 24-hour format, DateFormatter returns nil.

Sample screenshot attached for the time zone settings.

Answered by DTS Engineer in 801696022

This is a common trap. When working with fixed-format dates, you need to pin the local to en_US_POSIX. QA1480 NSDateFormatter and Internet Dates explains this in more detail.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

This is a common trap. When working with fixed-format dates, you need to pin the local to en_US_POSIX. QA1480 NSDateFormatter and Internet Dates explains this in more detail.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

DateFormatter not working, If I change the TimeZone in iPhone settings
 
 
Q