I'd like to parse string in MM-dd format to java date. Since year is not specified, parsed date should be in current year. Only valid date string should be parsed, so I should use setLenient(false)
in SimpleDateFormat
.
public static Date parseDate(String ds) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("MM-dd");
df.setLenient(false);
Date d = df.parse(ds);
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
cal.setTime(d);
cal.set(Calendar.YEAR, year);
return cal.getTime();
}
This seems to work well until I pass an argument "02-29". This year(2012) is leap year and 2012-02-29 is valid date, "02-29" should have been parsed successfully.
I found that when I don't specify year part in SimpleDateFormat
, it parse to year 1970. And 1970 is not a leap year, "02-29" fails to parse. So, parsing to date of year 1970 and set current year after parsing strategy is not perfect.
What is the best way to parse MM-dd format string to date (date should be set to current year) in Java?
PS1: I searched this topic and found many questions and answers in this site, but I couldn't find the satisfactory answer.
PS2: df.setLenient(false);
is important because only valid date string should be parsed successfully. Invalid date strings like "01-32", "02-30", etc. shouldn't be parsed.
Thanks in advance.
Get the year from the calendar as you do in the code, set the parse format string to
MM-dd-yyyy
and then doThis could be considered a little hacky, but you could always just tack the year onto the end of the date string before parsing, like this: