Java 8 – How to parse date with "dd MMM" (02 Jan), without year?
This example shows you how to parse a date (02 Jan) without a year specified.
JavaDateExample.java
package com.mkyong.time;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class JavaDateExample {
public static void main(String[] args) {
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: {DayOfMonth=2, MonthOfYear=1},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.mkyong.time.JavaDateExample.main(JavaDateExample.java:20)
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=2, MonthOfYear=1},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
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.mkyong.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 JavaDateExample {
public static void main(String[] args) {
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
Alternatively, if you don’t wish to store a year, you might also parse into the MonthDay type which is also part of the Java 8 time API