How can I parse a date (provided as a string) in the "ddMM" format and convert it to a Date Object in Java?

Shiv :

I am using the SimpleDateFormatter class to convert a string into a date. I have the following code which works for Feb 27, 2020:

SimpleDateFormat FORMATTER = new SimpleDateFormat("ddMM"); //always current year
Date TODAY = FORMATTER.parse("2702");
System.out.println(TODAY);

This resolves to the following date:

Fri Feb 27 00:00:00 UTC 1970

However, when I try the same for Feb 29, 2020 (a leap year), I get an error:

Code:

SimpleDateFormat FORMATTER = new SimpleDateFormat("ddMM"); //always current year
Date TODAY = FORMATTER.parse("2902");
System.out.println(TODAY);

Output:

Sun Mar 01 00:00:00 UTC 1970

Can someone please suggest a way so that I can take into account leap years as well, using this date format?

Thank you.

Andreas :

You should use the Java 8 Time API, because it supports specifying a default year.

public static Date dayMonthToDate(String dayMonth) {
    DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
            .appendPattern("ddMM")
            .parseDefaulting(ChronoField.YEAR, Year.now().getValue())
            .toFormatter();

    LocalDate localDate = LocalDate.parse(dayMonth, FORMATTER);
    Instant instant = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
    return Date.from(instant);
}

Test

public static void main(String[] args) {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

    System.out.println(dayMonthToDate("2702"));
    System.out.println(dayMonthToDate("2902"));
}

Output

Thu Feb 27 00:00:00 UTC 2020
Sat Feb 29 00:00:00 UTC 2020

Guess you like

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