0

We know US and GB have different date order. US is MM DD YYYY but GB is DD MM YYYY.

With SimpleDateFormat() class, we can define our pattern, for example "MM.dd.yyyy HH:mm:ss.SSS", i.e. new SimpleDateFormat("MM.dd.yyyy HH:mm:ss.SSS", myLocale); BUT the pattern is fixed. The order of the month and day will NOT change with US locale an GB locale.

Is there a way to define a custom format and the Locale will also affect the display order of the Month and Day?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
peterboston
  • 877
  • 1
  • 12
  • 24

1 Answers1

3

DateTimeFormatterBuilder.getLocalizedDateTimePattern

Use it to get formatting pattern for date and time styles for a locale and chronology.

Demo:

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.FormatStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
        System.out.println(now.format(DateTimeFormatter.ofPattern(getFullPattern(Locale.UK), Locale.ENGLISH)));
        System.out.println(now.format(DateTimeFormatter.ofPattern(getFullPattern(Locale.US), Locale.ENGLISH)));

        System.out.println(now.format(DateTimeFormatter.ofPattern(getShortPattern(Locale.UK))));
        System.out.println(now.format(DateTimeFormatter.ofPattern(getShortPattern(Locale.US))));
    }

    static String getFullPattern(Locale locale) {
        return DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.FULL, FormatStyle.FULL,
                IsoChronology.INSTANCE, locale);
    }

    static String getShortPattern(Locale locale) {
        return DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.SHORT, FormatStyle.SHORT,
                IsoChronology.INSTANCE, locale);
    }
}

Output:

Monday, 1 February 2021 at 21:05:34 Greenwich Mean Time
Monday, February 1, 2021 at 9:05:34 PM Greenwich Mean Time
01/02/2021, 21:05
2/1/21, 9:05 pm

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

Note: The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110