简体   繁体   中英

parsing MonthDate string in a leap year

please consider the following snippet:

    SimpleDateFormat parser = new SimpleDateFormat("MMdd");
    parser.setLenient(false);
    try {
        Date date = parser.parse("0229");
        System.out.println(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }

I have a text field which should contain a date in the format MMdd (no year, as it should always default to the current year).

This year, 2012, a leap year, I found myself in the strange situation of not being able to parse the valid date February 29th.

The calendar used by the code above always defaults to 1970, which, though luck, was not a leap year. Hence trying to parse "0229" always throws a parse exception.

Any idea on how to parse this?

附加当前年份并使用“ MMddyyyy”格式吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM