Date Formatting 24 hour

I would like to replace my use of DateFormatter with the new date.formatted(_) API but am having some difficulty.

For the context of the app in question, it is desirable to use twenty-four hour time regardless of what the user's personal settings are. I have code to do this below:

let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "\(dateFormatter.dateFormat!) HH:mm:ss"
return dateFormatter.string(from: date)

Is there a way to do this using the new API or do I need to continue using the old way?

Replies

AFAIK there’s no way to override the user’s preference using the new API. If that’s something you need, I encourage you to file an enhancement request describing your specific requirements. Please post your bug number, just for the record.

With regards your current code, I don’t think that actually works. Try this:

  1. In System Preferences > Language & Region > General, set your region to something that defaults to 24 hours (like the UK).

  2. Now uncheck the 24-Hour Time checkbox to force it to 12-hour time.

Your code returns something like this:

15/11/2021 4:26:27 pm

)-:

Share and Enjoy

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