Search code examples
kotlinjava-8localtimetime-format

How to format LocalTime with time-of-day abbreviation depending on device locale?


What's the best way to show a LocalTime value based on the device? The United States is the only nation that exclusively uses the AM/PM time of day abbreviation but for some reason the abbreviation does not appear whenever my device locale is set to the United States.

United States

2:30 AM / 2:30 PM

Elsewhere around the world

02:30 / 14:30

Current code

myTV.text = LocalTime.of(2, 30) + " " + LocalTime.of(14, 30)

Current result

2:30 14:30


Solution

  • You need to format your times explicitly. Use DateTimeFormatter.ofLocalizedTime.

        DateTimeFormatter localizedTimeFormatter
                = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
        LocalTime begin = LocalTime.of(2, 30);
        LocalTime end = LocalTime.of(14, 30);
    
        String text = begin.format(localizedTimeFormatter) + ' ' + end.format(localizedTimeFormatter);
        System.out.println(text);
    

    Sorry that I can write only Java code. When I ran the code on my desktop Java 9 with default locale set to US, the output was:

    2:30 AM 2:30 PM

    Output with other locales:

    • Canada: 2:30 AM 2:30 PM
    • UK or France: 02:30 14:30