Search code examples
java-8jodatimelocaldate

Parsing a year String to a LocalDate with Java8


With Joda library, you can do

DateTimeFormat.forPattern("yyyy").parseLocalDate("2008")

that creates a LocalDate at Jan 1st, 2008

With Java8, you can try to do

LocalDate.parse("2008",DateTimeFormatter.ofPattern("yyyy"))

but that fails to parse:

Text '2008' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2008},ISO of type java.time.format.Parsed

Is there any alternative, instead of specifically writing sth like

LocalDate.ofYearDay(Integer.valueOf("2008"), 1)

?


Solution

  • LocalDate parsing requires that all of the year, month and day are specfied.

    You can specify default values for the month and day by using a DateTimeFormatterBuilder and using the parseDefaulting methods:

    DateTimeFormatter format = new DateTimeFormatterBuilder()
         .appendPattern("yyyy")
         .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
         .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
         .toFormatter();
    
    LocalDate.parse("2008", format);