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

Time:10-14

Tests created previously use DateTimeFormatter.ofPattern("ha"); and returns "10AM" (for '2017-04-09T10:00-06:00[US/Mountain]').

Under my MacOs and Java ['openjdk version "11.0.12"'] I got "10am"

"10AM" != "10am"

In specification I see "ha" should create "10AM" not "10am" see: https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html

Any advice?

CodePudding user response:

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.

CodePudding user response:

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

solved issue

  • Related