How to sanity check a date in Java(如何在 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 中健全地检查日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中健全地检查日期


- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 转换 ldap 日期 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01