Validate range with java Date and SimpleDateFormat(使用 java Date 和 SimpleDateFormat 验证范围)
问题描述
当我在这里尝试使用此代码解析日期时,是否有可以处理的日期异常:
Is there a Date exception that I can deal with when I try to parse a date with this code here:
try{
SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy");
Date date = df.parse(dateRelease);
}catch (ParseException e) {}
好吧,如果dateRelease"是不是正确的格式类型,它会抛出 ParseException,但我想知道是否有人像2010 年 3 月 40 日"这样写.- 日、月或年无效范围错误.实际上,当发送无效日期时,SimpleDateFormat 只是使用默认数字创建一个新日期.
Well, if the "dateRelease" isn't in a correct format type it throws ParseException, but I want to get if someone write like "40/03/2010" - WRONG with day, month or year invalid range. Actually, when a invalid date is sent, SimpleDateFormat just create a new Date with default numbers.
我是否必须使用正则表达式创建自己的方法来处理它,或者是否存在告诉我它要捕获的现有异常?
Do I have to create my own method with a regex to deal with it or is there an existing exception that tells me it to catch?
推荐答案
通过 SimpleDateFormat#setLenient()
,值为 false
.
SimpleDateFormat df = new SimpleDateFormat("dd:MM:yyyy");
df.setLenient(false);
Date date = df.parse(dateRelease);
那么当日期不在有效范围内时会抛出ParseException
.
Then it will throw ParseException
when the date is not in a valid range.
这篇关于使用 java Date 和 SimpleDateFormat 验证范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 java Date 和 SimpleDateFormat 验证范围


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