如何使用Java 8 DateTimeFormatter更改解析两个字母年的基准日期? [英] How to change the base date for parsing two letter years with Java 8 DateTimeFormatter?

查看:435
本文介绍了如何使用Java 8 DateTimeFormatter更改解析两个字母年的基准日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用 d / M / yy 之类的模式来创建Java 8 DateTimeFormatter(例如使用 DateTimeFormatter.ofPattern(pattern); (我只用于解析,而不是格式化),它会将所有两个字母的年份解释为20xx,例如解析字符串,如 13/5/99 被解释为 2099-05-13 ,这在我的情况下是错误的(这是在1999年)。

If I use a pattern like d/M/yy for creating a Java 8 DateTimeFormatter (e.g. using DateTimeFormatter.ofPattern(pattern); (which I will only use for parsing, not formatting), it will interpret all two-letter years as 20xx, e.g. parsing a string like 13/5/99 to be interpreted as 2099-05-13, which in my case is wrong (it was meant to be in the year 1999).

在我的应用程序中,我正在尝试从OCR的文档中解析日期,例如仍然是从90年代起,因此将旧的SimpleDateFormat行为解释为80年以内在现在的日期之前和之后20年,我相当适合,但是由于各种原因,我仍然希望将整个日期解析逻辑切换到新的Java 8 DateTimeFormatters。

In my application, I'm trying to parse dates from OCR'd documents, which could e.g. still be from the 90ies, so having the old SimpleDateFormat behavior of interpreting the date to be within 80 years before and 20 years after the current date fits me quite well. But for various reasons I'm still looking to switch the whole date parsing logic to the new Java 8 DateTimeFormatters.

查看Java源代码,我看到这是相对于常量 ReducedPrinterParser.BASE_DATE 解释的,但是我看不到cha nge从模式构建我自己的格式化程序时使用的值。这是不可能的,或者我错过了一些指定解析两个字母年的行为的可能性?

Looking through the Java source code, I see that this is all interpreted relative to the constant ReducedPrinterParser.BASE_DATE, but I see no way to change the value used when building my own formatter from a pattern. Is this simply not possible or have I missed some possibility of specifying the behavior for parsing two-letter years?

推荐答案

您可以创建一个自定义的格式化程序,例如对于 d / M / yy 模式:

You can create a custom formatter, for example for the d/M/yy pattern:

new DateTimeFormatterBuilder()
        .appendPattern("d/M/")
        .appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2, LocalDate.now().minusYears(80))

使用示例:

public static void main(String[] args) throws Exception {
  DateTimeFormatter fmt = new DateTimeFormatterBuilder()
          .appendPattern("d/M/")
          .appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2, LocalDate.now().minusYears(80))
          .toFormatter();
  parse("13/5/99", fmt);
  parse("13/5/36", fmt);
  parse("13/5/35", fmt);
  parse("13/5/34", fmt);
  parse("13/5/33", fmt);
}

private static void parse(String date, DateTimeFormatter fmt) {
  System.out.println(date + " = " + LocalDate.parse(date, fmt));
}

打印:

13/5/99 = 1999-05-13

13/5/36 = 1936-05-13

13/5/35 = 1935-05-13

13/5/34 = 2034-05-13

13/5/33 = 2033-05-13

13/5/99 = 1999-05-13
13/5/36 = 1936-05-13
13/5/35 = 1935-05-13
13/5/34 = 2034-05-13
13/5/33 = 2033-05-13

这篇关于如何使用Java 8 DateTimeFormatter更改解析两个字母年的基准日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆