【问题标题】:How to show date without year based on locale in Java? [duplicate]如何根据Java中的语言环境显示没有年份的日期? [复制]
【发布时间】:2019-08-14 21:34:03
【问题描述】:

我使用 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

【问题讨论】:

标签: java date format locale


【解决方案1】:

本地化的 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 这样的 Temporal 对象。您需要将 java.util.Date 转换为这样的对象:

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

Date date = new Date();
String text = format.format(
    date.toInstant().atZone(ZoneId.systemDefault()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多