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

查看:115
本文介绍了如何在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天全站免登陆