Java 覆盖DateTimeFormatter面向century的本地化日期样式解析策略
我需要根据区域设置和格式样式动态解析日期字符串 例如,我有一个阿尔巴尼亚语言环境,其模式为yy-MM-dd 我有下面的代码,它基于当前的区域设置和格式样式来解析这个模式Java 覆盖DateTimeFormatter面向century的本地化日期样式解析策略,java,java-time,date-parsing,localdate,Java,Java Time,Date Parsing,Localdate,我需要根据区域设置和格式样式动态解析日期字符串 例如,我有一个阿尔巴尼亚语言环境,其模式为yy-MM-dd 我有下面的代码,它基于当前的区域设置和格式样式来解析这个模式 DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendLocalized(FormatStyle.SHORT, null) .toFormatter()
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()
的情况下,基于区域设置和格式样式的答案
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);
提前谢谢 在此基础上,您可以首先从输入字符串中提取模式,如下所示:
String shortPattern =
DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT,
null,
IsoChronology.INSTANCE,
Locale.forLanguageTag("sqi-AL")
);
System.out.println(shortPattern); //y-MM-d
现在,您可以使用特定的年份说明应用格式化程序。模式现在显式给出,删除了y
s,因为现在由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
追加可选的原因是,如果区域设置模式在末尾有年份,则可能导致解析错误。例如,代码中的区域设置模式(sq AL
)实际上是d.M.yy
。因此,我们需要检查两端的年份