Incorrect behavior in Date.FormatStyle

I just wasted quite a lot of time on this .. so in case somebody else checks in here, beware that the following:

formatted(dateTime.hour(.defaultDigits(amPM: .omitted)))

does, indeed omit AM/PM, but it doesn't change to using a 24 hour clock. Instead, hours cycle through 1...12 twice a day.

I’m not sure why you think that’s incorrect behaviour: You asked it to omit the clock period marker and that’s exactly what it did.

As to what you should do, that depends on whether you want:

  • A localised hour value but overriding the default clock period style to 24-hour.

  • An non-localised hour value that runs from 0 through 23.

Share and Enjoy

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

Add the hours attribute to your locale identifier (e.g., "en_US@hours=h23") with one of these values to get what you want:

h12 Hour system using 1–12; corresponds to 'h' in patterns. The 12 hour clock, with midnight starting at 12:00 am. As used, for example, in the United States.

h23 Hour system using 0–23; corresponds to 'H' in patterns. The 24 hour clock, with midnight starting at 0:00.

h11 Hour system using 0–11; corresponds to 'K' in patterns. The 12 hour clock, with midnight starting at 0:00 am. Mostly used in Japan.

h24 Hour system using 1–24; corresponds to 'k' in pattern. The 24 hour clock, with midnight starting at 24:00. Not used anywhere.

Thanks both. I live, learn and appreciate .. and, even a grumpy 3am forum entry title should say "unexpected" and not "Incorrect" .. apologies.

Add the hours attribute to your locale identifier

Neat! Although this assumes that you want to present the string to the user. For non-localised stuff, check out Date.VerbatimFormatStyle.

Share and Enjoy

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

.. for any one else arriving here, I suggest reading extensive, excellent commentary about this topic at:

https://forums.swift.org/t/new-date-formatstyle-anyway-to-do-24-hour/52994

Incorrect behavior in Date.FormatStyle
 
 
Q