How do I format am-pm-of-day to be "AM/PM" rather than "a.m./p.m."?

DateTimeFormatter's API reference seems to miss details for formatting am-pm-of-day properly, I could always use String.replace() but I feel like it makes more sense to have an option change a.m. to AM and/or p.m. to PM using "aaa...". Is there a way to do this?


Solution 1:

Localized per CLDR

When formatting the textual representation of a date-time object, decisions about capitalization and abbreviation are matters left to the rules of localization. Those rules are defined as part of a Locale object. In the latest versions of Java built on the codebase of the OpenJDK project, the Locale class gets its localization data from the Common Locale Data Repository (CLDR) maintained by the Unicode Consortium.

So no, there is no way to specify use of “AM” versus “a.m.” other than to specify one Locale object versus another.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "Asia/Tokyo" ) ) ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.MEDIUM ) ;
String outputCaFr = zdt.format( f.withLocale( Locale.CANADA_FRENCH ) ) ;
String outputUkEn = zdt.format( f.withLocale( Locale.UK) ) ;

If you insist on a particular format, you’ll have to do the string manipulation yourself. But I suggest letting Locale, DateTimeFormatter, and the CLDR do their work of localizing rather than hard-coding trivial formatting tweaks.