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

查看:33
本文介绍了如何在 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 a not so obvious to use lenient calendar.

如何检查以日、月和年的组合形式给出的日期是否是有效日期?

How do you check that a date, given as a combination of day, month, and year, is a valid date?

例如,2008-02-31(如 yyyy-mm-dd)将是无效日期.

For instance, 2008-02-31 (as in yyyy-mm-dd) would be an 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天全站免登陆