[英]Overwrite DateTimeFormatter localized date style parsing strategy for century
我需要根据语言环境和格式样式动态解析日期字符串。
例如,我有一个阿尔巴尼亚语言环境,它的模式为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()
并且基于语言环境和格式样式的答案
提前致谢!
以此答案为基础,您可以首先从输入字符串中提取模式,如下所示:
String shortPattern =
DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT,
null,
IsoChronology.INSTANCE,
Locale.forLanguageTag("sqi-AL")
);
System.out.println(shortPattern); //y-MM-d
现在,您可以使用具有特定年份说明的格式化程序。 由于 year 现在由appendValueReduced
处理, appendValueReduced
现在明确给出了模式,并删除了y
s:
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
) 中语言环境的模式实际上是dMyy
。 所以我们需要在两端检查年份。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.