我使用 DateFormat 和语言环境来显示日和月。 DateFormat 支持 MEDIUM, LONG, FULL 都有年份。我只想显示月份和日期。
我尝试使用 SimpleDateFormat,但 SimpleDateFormat 定义了月和日的顺序。在不同的国家,日期格式是不同的。我不想定义月和日的顺序。我希望日期格式由语言环境决定。
这是我的代码,如何从日期中删除年份?
Locale myLocale =Locale.FRANCE;
DateFormat localFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM, myLocale);
String localDate = localFormatter.format(date);
我尝试了以下语言环境并在右侧打印日期:
Locale myLocale =Locale.FRANCE; localDate=1 avr. 2018
Locale myLocale =Locale.CHINA; localDate=2018-4-1
Locale myLocale =Locale.JAPAN; localDate=2018/04/01
一个本地化的 DateFormat 可能是也可能不是一个 SimpleDateFormat,所以你不能确定它会有一个模式。但是,您可以获得本地化的 DateTimeFormatter模式,并从中去掉年份:
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();
}
但是有一个问题。返回的 Format 无法格式化 Date 或 Calendar 对象。它需要像 LocalDate 或 ZonedDateTime 这样的时间对象。您需要将 java.util.Date 转换为此类对象:
Format format = createMonthDayFormat(FormatStyle.SHORT, Locale.getDefault());
Date date = new Date();
String text = format.format(
date.toInstant().atZone(ZoneId.systemDefault()));