DateFormatter returns the unexpected formate when run on iPhone Xs Max with iOS 13.3.1

With the date time being 1:02:27 pm and formatting using the following code,


func getDateTimeStringFromDate() -> String {

let formatter = DateFormatter()

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.000Z"

return formatter.string(from: self)

}


I was expecting the function to return the string with the "HH:mm:ss" part being 13:02:27, instead it returns 1:02:27. Notice not only it did not return the time in a 24 hour system, it also removed the leading 0 of the hour. Does anyone know what is causing this?

Accepted Reply

Apple's document of DateFormatter recommends us to set `locale` to `

Locale(identifier: "en_US_POSIX")
` when using fixed format like yours.


https://developer.apple.com/documentation/foundation/dateformatter


What do you get if you set `locale` as shown in the doc?

    func getDateTimeStringFromDate() -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.000Z"
        return formatter.string(from: self)
    }

Replies

Apple's document of DateFormatter recommends us to set `locale` to `

Locale(identifier: "en_US_POSIX")
` when using fixed format like yours.


https://developer.apple.com/documentation/foundation/dateformatter


What do you get if you set `locale` as shown in the doc?

    func getDateTimeStringFromDate() -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.000Z"
        return formatter.string(from: self)
    }