Date and time getting fail to convert in 24 hour, after change format in 12 hour from device setting

I have been working on a Calendar App. i am getting date format 2023-08-25T7:07:00 pm which is not parsing in any date format.

Required Output: 2023-08-25T19:07:00

Getting fail with all date formatter Here is the my code snippet

let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss a" dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone.current if let date = dateFormatter.date(from: dateString) { let formattedDateString = dateFormatter.string(from: date) print(formattedDateString) } else { print("Invalid date format") }

Help me on this.

  • Here is the iOS version which we are using iOS 16.6 and Region Region(calendar: Calendars.gregorian, zone: Zones.europeLondon, locale: Locales.englishUnitedKingdom)

Add a Comment

Replies

First, in the future be sure to use code block formatting, like this:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss a"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.current

if let date = dateFormatter.date(from: dateString) {
    let formattedDateString = dateFormatter.string(from: date)
    print(formattedDateString)
} else {
    print("Invalid date format") 
}

Then look closely at Technical Q&A QA1480: NSDateFormatter and Internet Dates. This point is important:

Once you've set "en_US_POSIX" as the locale of the date formatter, you can then set the date format string

So you should set the formatter’s locale before you set dateFormat.

i am getting date format 2023-08-25T7:07:00 pm

Just curious, what is generating dates in that format? It sort of resembles ISO 8601 format, but isn’t. If you are the one designing the wire format for dates in your system (between your back end and your app, for example) then ISO 8601 is the way to go.