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

查看:29
本文介绍了如何使用 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 年代,因此将日期解释为当前日期之前 80 年和之后 20 年的旧 SimpleDateFormat 行为非常适合我.但出于各种原因,我仍然希望将整个日期解析逻辑切换到新的 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 进行解释的,但是我认为无法更改从模式构建我自己的格式化程序时使用的值.这是根本不可能的还是我错过了一些指定解析两个字母年份的行为的可能性?

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天全站免登陆