Home > Back-end >  Java DateTimeFormat style: how to use 24 hours instead of AM/PM?
Java DateTimeFormat style: how to use 24 hours instead of AM/PM?

Time:11-14

Java DateTimeFormat style: how to use 24 hours instead of AM/PM?

    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.US);
    String date = dateFormat.format(new Date());
    System.out.print(date);

Output:

 11/13/21 6:41:43 PM

Need to be:

 11/13/21 18:41:43

Tried DateTimeFormatter, got same result:

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.MEDIUM);
    formatter.withLocale(Locale.US);
    String time = formatter.format(LocalDateTime.now());

This is for all different locales, so pattern will not work. Locale.US is an example only.

CodePudding user response:

You should first check if the date string matches any of the Predefined Formatters.

If not, then you have to make your own Formatter using .ofPattern(String pattern) or .ofPattern(String pattern, Locale locale):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yy HH:mm:ss", Locale.US);

System.out.println(formatter.format(LocalDateTime.now()));

Output:

11/13/21 19:41:43

CodePudding user response:

24-hour time not appropriate for some locales

If localizing for the United States, then you should not be aiming for 24-hour time. 24-hour time is generally not used in the US outside of the military. Indeed, Americans often refer to it as "military time".

So your two statements "how to use 24 hours instead of AM/PM?" and "This is for all different locales" are contradictory. You cannot have it both ways. Either you want to control the output such as forcing 24 hour clock, or you want to localize.

If you really need a specific format, use the Answer by lkatiforis. But if your goal is to localize automatically, then you have to "go with the flow" regarding the results. Some locales will localize to 24-hour clock, and some locales will localize to 12-hour clock.

If you want to know where Java gets its rules for how to localize date-time values (translation, and cultural norms), see the Common Locale Data Repository (CLDR) maintained by the Unicode Consortium. The CLDR is used by default in most implementations of Java 9 and later.

If you want to see the various locales in action, here is some example code.

LocalDateTime ldt = LocalDateTime.of( 2021 , 1 , 23 , 18 , 30 , 45 , 0 );
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT );
for ( Locale locale : Locale.getAvailableLocales() )
{
    String output = ldt.format( f.withLocale( locale ) );
    System.out.println( output   " | "   locale.getDisplayName( Locale.US )   " | "   locale );
}

When run.

…
23.01.21 18:30 | Latvian | lv
23/01/2021, 18:30 | English (Niue) | en_NU
23/01/21 下午6:30 | Chinese (Simplified, Singapore) | zh_SG_#Hans
2021-01-23 6:30            
  • Related