java - 覆盖DateTimeFormatter本世纪的本地化日期样式解析策略

标签 java java-time date-parsing localdate

我需要根据区域设置和格式样式动态解析日期字符串。

例如,我有一个阿尔巴尼亚语言环境,其模式为 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/

相关文章:

java - 在 Eclipse 中运行程序时播放音乐,但在运行 Jar 可执行文件时不播放

java - 我想通过 JAXB 将带有 java.time.Localdate (JSR-310) 的对象转换为 XML,但输出错误

javascript - 使用 Moment.js 格式化日期

java测试: accelerate time to test timeouts?

java - 无法从 BLE nordic thingy :52 检索 RSSI 值

java - 当文本更改时如何阻止 JLabel 更改其大小?

java - 从包含周名和时间的字符串中解析时间

java - 在开头创建一个带有可选部分的 DateTimeFormater

javascript - 在 Javascript 中使用 new Date ("2014 Aug 11") 和 new Date ("2014-08-11") 时的不同日期

java -/日期(长+1000)/格式