[英]Overwrite DateTimeFormatter localized date style parsing strategy for century
I need to parse the date string dynamically based on the locale and format style.我需要根据语言环境和格式样式动态解析日期字符串。
For example, I have an Albanian locale which has pattern yy-MM-dd例如,我有一个阿尔巴尼亚语言环境,它的模式为yy-MM-dd
I have following code which resolves this pattern basing on the current locale and format style我有以下代码可以根据当前的语言环境和格式样式解决此模式
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);
The input string is parsed as 09/07/2092输入字符串被解析为09/07/2092
But I need to parse this date as 09/07/1992但我需要将此日期解析为09/07/1992
Adding the code for .appendValueReduced
doesn't work添加.appendValueReduced
的代码不起作用
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendLocalized(FormatStyle.SHORT, null)
.appendValueReduced(ChronoField.YEAR, 2, 2, LocalDate.now().minusYears(80))
.toFormatter()
.withLocale(Locale.forLanguageTag("sq-AL"));
I've searched for answers on StackOverflow but did not find any that works without .appendPattern()
and based on the locale and format style我已经在 StackOverflow 上搜索了答案,但没有找到任何没有.appendPattern()
并且基于语言环境和格式样式的答案
Thanks in advance!提前致谢!
Building up on this answer , you can first extract the pattern from the input string like so: 以此答案为基础,您可以首先从输入字符串中提取模式,如下所示:
String shortPattern =
DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT,
null,
IsoChronology.INSTANCE,
Locale.forLanguageTag("sqi-AL")
);
System.out.println(shortPattern); //y-MM-d
Now you can apply your formatter with specific year instructions.现在,您可以使用具有特定年份说明的格式化程序。 The pattern now is given explicitly with the y
s removed since year is now being handled by appendValueReduced
:由于 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
The reason for appendOptional
is that if the locale pattern has year at the end, it could lead to parse error. appendOptional
的原因是,如果语言环境模式以年份结尾,则可能会导致解析错误。 For example, the pattern for the locale in your code( sq-AL
) is actually dMyy
.例如,您的代码 ( sq-AL
) 中语言环境的模式实际上是dMyy
。 So we need to check for year at both ends.所以我们需要在两端检查年份。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.