3

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?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
THM
  • 579
  • 6
  • 25
  • It depends on the locale used and in the end also on the locale data and hence on the locale data provider. See for example [java.text.ParseException: Unparseable date: "01:19 PM"](https://stackoverflow.com/questions/25524284/java-text-parseexception-unparseable-date-0119-pm) – Ole V.V. Oct 14 '21 at 06:46
  • Which is the default locale in Java on your Mac? (`System.out.println(Locale.getDefault(Locale.Category.FORMAT));`) – Ole V.V. Oct 14 '21 at 07:13

2 Answers2

8

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1
-Duser.timezone=EDT
-Duser.country=US
-Duser.language=en-US

solved issue

THM
  • 579
  • 6
  • 25
  • 1
    I think that the last one `-Duser.language=en-US`, is decisive here. You may try with it alone. Or keep all three if you like them. – Ole V.V. Oct 14 '21 at 07:19
  • 2
    Don’t use EDT as a time zone. One, it is not, two, three letter time zone abbreviations are ambiguous, more often than not. Three, no place uses Eastern Daylight Time (which I guess you intended) all year. Use for example `America/New_York`. Always use *region/city* format for time zones. – Ole V.V. Oct 14 '21 at 07:25