How to change the base date for parsing two letter years with Java 8 DateTimeFormatter?

后端 未结 1 1699
自闭症患者
自闭症患者 2020-12-01 19:31

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

相关标签:
1条回答
  • 2020-12-01 19:42

    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))
    

    Example usage:

    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));
    }
    

    which prints:

    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

    0 讨论(0)
提交回复
热议问题