2

I use DateFormat and locale to show Day and Month. DateFormat supports MEDIUM, LONG, FULL all have a year.I only want to show month and day.

I tried to use SimpleDateFormat, but SimpleDateFormat defined the order of month and day. In different countries, date format is different. I don't want to define the order of month and day. I hope the date format is decided by locale.

Here is my code and how can I remove year from the date?

Locale myLocale =Locale.FRANCE;

DateFormat localFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM, myLocale);

String   localDate     = localFormatter.format(date);

I tried the following locale and print the date on the right:

Locale myLocale =Locale.FRANCE; localDate=1 avr. 2018

Locale myLocale =Locale.CHINA; localDate=2018-4-1

Locale myLocale =Locale.JAPAN; localDate=2018/04/01
nishantc1527
  • 376
  • 1
  • 12
Judy
  • 41
  • 5
  • Feature Request: [*Formatting YearMonth or MonthDay using DateTimeFormatter with different Locales FAILS*](https://bugs.openjdk.java.net/browse/JDK-8168532) – Basil Bourque Aug 15 '19 at 22:26

1 Answers1

0

A localized DateFormat may or may not be a SimpleDateFormat, so you can’t be certain it will have a pattern. However, you can obtain a localized DateTimeFormatter pattern, and strip the year from that:

public static Format createMonthDayFormat(FormatStyle style,
                                          Locale locale) {
    String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
        style, null, Chronology.ofLocale(locale), locale);
    pattern = pattern.replaceFirst("\\P{IsLetter}+[Yy]+", "");
    pattern = pattern.replaceFirst("^[Yy]+\\P{IsLetter}+", "");

    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern(pattern, locale);
    return formatter.toFormat();
}

There is a catch, however. The returned Format cannot format Date or Calendar objects. It expects Temporal objects like LocalDate or ZonedDateTime. You will need to convert a java.util.Date to such an object:

Format format = createMonthDayFormat(FormatStyle.SHORT, Locale.getDefault());

Date date = new Date();
String text = format.format(
    date.toInstant().atZone(ZoneId.systemDefault()));
VGR
  • 40,506
  • 4
  • 48
  • 63