Take the 2-minute tour ×

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");
    Date d = df.parse(ds);
    Calendar cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    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.

share|improve this question
You could use "yyyy-MM-dd" and add the actual year in the String before parsing it. –  Luiggi Mendoza Jul 15 '12 at 16:31
Could you explain why you just unaccepted my answer? –  Jake King Dec 31 '12 at 17:20
add comment

2 Answers

This 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:

ds += "-" + Calendar.getInstance().get(Calendar.YEAR);
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
// Parse date as usual
share|improve this answer
Date#getYear() is a deprecated method. You should never use it because it could dissapear in future Java releases. –  Luiggi Mendoza Jul 15 '12 at 16:37
@LuiggiMendoza Fixed. –  Jake King Jul 15 '12 at 16:52
add comment

Get the year from the calendar as you do in the code, set the parse format string to MM-dd-yyyy and then do

 Date d = df.parse(ds + "-" + year);
share|improve this answer
add comment

Your Answer


