How to convert two digit year to full year using Java 8 time API

前端 未结 5 1087
渐次进展
渐次进展 2021-01-17 17:41

I wish to remove the Joda-Time library from my project.

I am trying to convert a two digit year to full year. The following code from Joda-Time can fulfil the purpos

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-17 18:27

    You need to provide default values for DAY_OF_MONTH and MONTH_OF_YEAR

    DateTimeFormatter TWO_YEAR_FORMATTER = new DateTimeFormatterBuilder()
                    .appendPattern("yy")
                    .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
                    .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                    .toFormatter();
    

    In addition,

    Java-8 uses the range 2000-2099 per default, not like SimpleDateFormat the range -80 years until +20 years relative to today.

    Full answer

    Since you're parsing years only, in order to have '99' as '1999' your code should be like this:

    DateTimeFormatter TWO_YEAR_FORMATTER = new DateTimeFormatterBuilder()
                    .appendPattern("")
                    .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
                    .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                    .appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2, LocalDate.now().minusYears(80))
                    .toFormatter();
    

提交回复
热议问题