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

前端 未结 5 1088
渐次进展
渐次进展 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:44

    The problem is that you can't parse a year on its own into a LocalDate. A LocalDate needs more information than that.

    You can use the parse method of the formatter, which will give you a TemporalAccessor, and then get the year field from that:

    int year = TWO_YEAR_FORMATTER.parse("99").get(ChronoField.YEAR);
    System.out.println(year);
    

    Addressing the discrepancy between the two: these are two distinct APIs. Yes, they are very similar, and the java.time package was informed by design decisions of JodaTime, but it was never intended to be a drop-in replacement for it.

    See this answer if you would like to change the pivot year (by default '99' will resolve to 2099 and not 1999).

提交回复
热议问题