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

Deb :

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 purpose. Below is the following code of joda-time

DateTimeFormatter TWO_YEAR_FORMATTER = DateTimeFormat.forPattern("yy");
int year = LocalDate.parse("99"", TWO_YEAR_FORMATTER).getYear();
System.out.println(year);

Output: 1999

This is the output that I expect and that makes sense in my situation. However, when I try the same procedure with java.time API, it produces a DatetimeParseException. Below is the following code of java.time API:

DateTimeFormatter TWO_YEAR_FORMATTER = DateTimeFormatter.ofPattern("yy");
int year = LocalDate.parse("99", TWO_YEAR_FORMATTER).getYear();
System.out.println(year);

Stacktrace:

Exception in thread "main" java.time.format.DateTimeParseException: Text '99' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2099},ISO of type java.time.format.Parsed
    at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
    at java.base/java.time.LocalDate.parse(LocalDate.java:428)
    at scratch.main(scratch.java:10)
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {Year=2099},ISO of type java.time.format.Parsed
    at java.base/java.time.LocalDate.from(LocalDate.java:396)
    at java.base/java.time.format.Parsed.query(Parsed.java:235)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    ... 2 more

I failed to see the reason of the stacktrace. It would be nice if someone could help me out to understand the following scenario and also explain how to convert a two digit year to full year using Java 8 time API.

Michael :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=37112&siteId=1