1
    LocalDateTime today = LocalDateTime.now();
    String timeMedium = today.format(DateTimeFormatter
            .ofLocalizedTime(FormatStyle.MEDIUM));
    System.out.println("timeMedium = " + timeMedium);

In this code, we expect output something like that timeMedium = 1:12:50 AM. It shows AM/PM in many pc with the same java version (16). The code should work the same as java 8 and above. But in my pc (MacOS Catalina), AM/PM never shows up. It is also the same for the below code.

    ZonedDateTime today = ZonedDateTime.now();
    String timeMedium = today.format(DateTimeFormatter
            .ofLocalizedTime(FormatStyle.LONG));
    System.out.println("timeMedium = " + timeMedium);

Output will be something like that timeMedium = 1:11:35 a.m. EDT. It works fine in Ubuntu 20.04. But in my mac it shows without AM/PM.

N.B.- My PC is setup with 12 hour time format.

  • 4
    `timeMedium = 10:06:40 am` shows up on my Mac – MadProgrammer May 18 '21 at 00:06
  • That's true @MadProgrammer. In other macs, am/pm shows up but not mine. I don't know why. – Md. Nowshad Hasan May 18 '21 at 00:18
  • 2
    Then I would consider it an issue with your Mac. You'd have to dig into the source code Java to try and figure out where it's pulling the localisation information from – MadProgrammer May 18 '21 at 00:19
  • Is your system configured for 24h time? If so then the `am` would not be shown, because 1:12pm for example would show as 13:12 instead. – sorifiend May 18 '21 at 02:24
  • 1
    The result depends on the locale of the PC, so you're running with a different locale than the other machines. To fix, explicitly specify the locale, e.g. `.ofLocalizedTime(FormatStyle.LONG).withLocale(Locale.US));` --- *FYI:* Java doesn't use the format setting of the PC, only the locale. Java uses it's own internal formatting rules, as selected by that locale. --- Alternatively, if you don't want to modify the code, see: [How do I set the default locale in the JVM?](https://stackoverflow.com/q/8809098/5221149) – Andreas May 18 '21 at 03:08

1 Answers1

0

Locale

It’s a matter of using the desired locale. Java does not pick up the 12 hours or 24 hours setting of the underlying operating system (macOS in your case). It often picks up the locale of the OS but is not guaranteed to do it always. So the bullet-proof solution is to specify locale in your Java code. For example for Bengali locale:

    ZonedDateTime today = ZonedDateTime.now(ZoneId.of("Asia/Dhaka"));
    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG)
                    .withLocale(Locale.forLanguageTag("bn-BD"));
    String timeLong = today.format(timeFormatter);
    System.out.println("timeLong = " + timeLong);

Example output:

timeLong = 9:11:57 AM BDT

Link (thanks, Andreas): How do I set the default locale in the JVM?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161