我需要根据区域设置和格式样式动态解析日期字符串。
例如,我有一个阿尔巴尼亚语言环境,其模式为 yy-MM-dd
我有以下代码,它根据当前区域设置和格式样式解析此模式
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendLocalized(FormatStyle.SHORT, null)
.toFormatter()
.withLocale(Locale.forLanguageTag("sq-AL"));
TemporalAccessor temporalAccessor = formatter.parseBest("92-07-09", LocalDateTime::from, LocalDate::from, LocalTime::from);
System.out.println(temporalAccessor);
输入字符串被解析为09/07/2092
但我需要将此日期解析为 09/07/1992
添加 .appendValueReduced
代码不起作用
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendLocalized(FormatStyle.SHORT, null)
.appendValueReduced(ChronoField.YEAR, 2, 2, LocalDate.now().minusYears(80))
.toFormatter()
.withLocale(Locale.forLanguageTag("sq-AL"));
我在 StackOverflow 上搜索了答案,但没有找到任何无需 .appendPattern()
且基于区域设置和格式样式的答案
提前致谢!
最佳答案
以 this answer 为基础,您可以首先从输入字符串中提取模式,如下所示:
String shortPattern =
DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT,
null,
IsoChronology.INSTANCE,
Locale.forLanguageTag("sqi-AL")
);
System.out.println(shortPattern); //y-MM-d
现在您可以应用具有特定年份说明的格式化程序。现在,该模式已明确给出,并删除了 y
,因为年份现在由 appendValueReduced
处理:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ofPattern(shortPattern.replaceAll("y","")))
.appendValueReduced(ChronoField.YEAR, 2, 4, LocalDate.now().minusYears(80))
.appendOptional(DateTimeFormatter.ofPattern(shortPattern.replaceAll("y","")))
.toFormatter();
TemporalAccessor temporalAccessor = formatter.parseBest("92-07-09", LocalDate::from, LocalDateTime::from);
System.out.println(temporalAccessor); //1992-07-09
使用appendOptional
的原因是,如果语言环境模式末尾有年份,则可能会导致解析错误。例如,代码中区域设置的模式 (sq-AL
) 实际上是 d.M.yy
。所以我们需要检查两端的年份。
关于java - 覆盖DateTimeFormatter本世纪的本地化日期样式解析策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59583417/