将日期字符串(MM-dd)解析为默认年份中的java日期 [英] Parsing date string (MM-dd) to java date in default year

查看:470
本文介绍了将日期字符串(MM-dd)解析为默认年份中的java日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将MM-dd格式的字符串解析为java日期。由于未指定年份,因此解析日期应为当年。只应解析有效的日期字符串,因此我应该在 SimpleDateFormat 中使用 setLenient(false)

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();
}

这似乎工作得很好,直到我传递一个参数02-29。今年(2012年)是闰年,2012-02-29是有效日期,02-29应该已成功解析。

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.

SimpleDateFormat 中指定年份部分,它解析为1970年。1970年不是闰年,02-29无法解析。因此,解析到1970年的日期,并在解析策略后设置当前年份不完美。

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.

解析MM-dd格式字符串的最佳方法是什么日期(日期应设为当前年份)在Java?

PS1:我搜索了这个主题,在这个网站上发现了很多问题和答案,找不到满意的答案。
PS2: df.setLenient(false); 很重要,因为只有有效的日期字符串应该被成功解析。

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.

提前感谢。

推荐答案

这可能被认为是一个小小的黑客,但你可以总是只是在解析之前的日期字符串的末尾,如下:

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

这篇关于将日期字符串(MM-dd)解析为默认年份中的java日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆