我尝试了相反的方法:使用本地化的格式化程序格式化日期。
LocalDate testDate = LocalDate.of(2017, Month.APRIL, 1);
final DateTimeFormatter englishFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.ENGLISH);
System.out.println("English: " + testDate.format(englishFormatter));
final DateTimeFormatter germanFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.GERMAN);
System.out.println("German: " + testDate.format(germanFormatter));
I got
English: 4/1/17
German: 01.04.17
因此很明显,Java 认为标准德语日期格式使用前导零。如果您确定这是错误的,您可以考虑向 Oracle 提交错误。
为了避免您不喜欢的行为,在多个区域设置中,我担心您需要某种破解。我能想到的最好的技巧如下。这并不美丽。有用。
private static final Map<Locale, DateTimeFormatter> STEFFI_S_LOCALIZED_FORMATTERS
= createSteffiSFormatters();
private static Map<Locale, DateTimeFormatter> createSteffiSFormatters() {
Map<Locale, DateTimeFormatter> formatters = new HashMap<>(2);
formatters.put(Locale.GERMAN, DateTimeFormatter.ofPattern("d.M.uu"));
return formatters;
}
public static DateTimeFormatter getLocalizedFormatter(Locale formattingLocale) {
DateTimeFormatter localizedFormatter
= STEFFI_S_LOCALIZED_FORMATTERS.get(formattingLocale);
if (localizedFormatter == null) {
localizedFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(formattingLocale);
}
return localizedFormatter;
}
现在你可以这样做:
final DateTimeFormatter englishFormatter = getLocalizedFormatter(Locale.ENGLISH);
System.out.println(LocalDate.parse("04/01/17", englishFormatter));
System.out.println(LocalDate.parse("4/1/17", englishFormatter));
final DateTimeFormatter germanFormatter = getLocalizedFormatter(Locale.GERMAN);
System.out.println(LocalDate.parse("01.04.17", germanFormatter));
System.out.println(LocalDate.parse("1.4.17", germanFormatter));
这打印:
2017-04-01
2017-04-01
2017-04-01
2017-04-01