问题描述
我们知道美国和英国有不同的日期顺序。美国是 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也会影响月和日的显示顺序?
解决方法
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,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。
- 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7。
- 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。