如何正确检查在java中的日期 [英] How to sanity check a date in java

查看:347
本文介绍了如何正确检查在java中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现很好奇,在Java中创建Date对象的最明显的方法已经被弃用,似乎已经被替换而不是那么明显使用宽松日历。所以...

I find it curious that the most obvious way to create Date objects in Java has been deprecated and appears to have been "substituted" with not so obvious to use lenient calendar. So...

如何检查日期,月份和年份的组合是否为有效日期?例如,日期2008-02-31(如yyyy-mm-dd)将是无效日期。

How do you check that a date given as a combination of day, month and year is a valid date? For instance a date 2008-02-31 (as in yyyy-mm-dd) would be invalid date.

推荐答案

当前的方式是使用日历类。它有 setLenient 方法将验证日期,抛出和异常,如果它超出范围,如在你的示例中。

The current way is to use the calendar class. It has the setLenient method that will validate the date and throw and exception if it is out of range as in your example.

忘记添加:
如果您获得日历实例,并使用日期设置时间,则这是您如何进行验证。

Forgot to add: If you get a calendar instance and set the time using your date, this is how you get the validation.

Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(yourDate);
try {
    cal.getTime();
}
catch (Exception e) {
  System.out.println("Invalid date");
}

这篇关于如何正确检查在java中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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