How to change time format in Java - "am/pm" vs. "AM/PM"

Viewed 349
2 Answers

DateTimeFormatter is a Locale-sensitive type i.e. its parsing and formatting depend on the Locale. Check Never use SimpleDateFormat or DateTimeFormatter without a Locale to learn more about it.

If you have an English Locale, and you want the output to be always in a single case (i.e. upper case), you can chain the string operation with the formatted string e.g.

import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        System.out.println(
                LocalTime.now(ZoneOffset.UTC)
                    .format(DateTimeFormatter.ofPattern("ha", Locale.ENGLISH))
                    .toUpperCase()
        );
    }
}

Output from a sample run:

6AM

ONLINE DEMO

Learn more about the modern Date-Time API* from Trail: Date Time.


* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.

-Duser.timezone=EDT
-Duser.country=US
-Duser.language=en-US

solved issue

Related