【问题标题】:how to make a custom date format which will change the MMdd order base on the Locale (US or GB)如何制作自定义日期格式,该格式将根据区域设置(美国或英国)更改 MMdd 订单
【发布时间】:2021-05-06 01:17:57
【问题描述】:

我们知道美国和英国有不同的日期顺序。美国是 MM DD YYYY,但 GB 是 DD MM YYYY。

使用 SimpleDateFormat() 类,我们可以定义我们的模式,例如“MM.dd.yyyy HH:mm:ss.SSS”,即 new SimpleDateFormat("MM.dd.yyyy HH:mm:ss.SSS", myLocale);但是模式是固定的。月份和日期的顺序不会随美国语言环境和 GB 语言环境而改变。

有没有办法定义自定义格式,Locale 也会影响月和日的显示顺序?

【问题讨论】:

  • 永远不要使用DateCalendarSimpleDateFormat。仅使用 JSR 310 中定义的 java.time 类。

标签: java date internationalization locale datetime-format


【解决方案1】:

DateTimeFormatterBuilder.getLocalizedDateTimePattern

使用它来获取区域设置和年表的日期和时间样式的格式模式。

演示:

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);
    }
}

输出:

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

通过 Trail: Date Time 了解有关现代日期时间 API 的更多信息。

注意:java.util 的日期时间 API 及其格式 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,转用modern date-time API

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多