This example shows you how to parse a date (02 Jan) without a year specified.

JavaDateExample.java

package com.favtuts.time;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class ParseDateWithoutYear {

    public static void main(String[] args) {
        parseDateFailed();
    }

    static void parseDateFailed() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM", Locale.US);

        String date = "02 Jan";

        LocalDate localDate = LocalDate.parse(date, formatter);

        System.out.println(localDate);

        System.out.println(formatter.format(localDate));
    }
}

Output

Exception in thread "main" java.time.format.DateTimeParseException: Text '02 Jan' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=1, DayOfMonth=2},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 com.favtuts.time.ParseDateWithoutYear.parseDateFailed(ParseDateWithoutYear.java:18)
        at com.favtuts.time.ParseDateWithoutYear.main(ParseDateWithoutYear.java:10)
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=1, DayOfMonth=2},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)
        ... 3 more

Solution

The pattern dd MMM is not enough; we need a DateTimeFormatterBuilder to provide a default year for the date parsing.

JavaDateExample.java

package com.favtuts.time;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;

public class ParseDateWithoutYear {

    public static void main(String[] args) {
        parseDateSuccess();
    }

    static void parseDateSuccess() {
        //DateTimeFormatterBuilder to provide a default year for the date parsing
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern("dd MMM")
                .parseDefaulting(ChronoField.YEAR, 2020)
                .toFormatter(Locale.US);

        String date = "02 Jan";

        LocalDate localDate = LocalDate.parse(date, formatter);

        System.out.println(localDate);

        System.out.println(formatter.format(localDate));
    }
}

Output

2020-01-02
02 Jan

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-basic/time

References

Leave a Reply

Your email address will not be published. Required fields are marked *