使用java Date和SimpleDateFormat验证范围 [英] Validate range with java Date and SimpleDateFormat

查看:144
本文介绍了使用java Date和SimpleDateFormat验证范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计们,我想知道当我尝试使用此代码解析日期时是否有我可以处理的Date例外:

Hey guys, I would like to know if there is 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) {} 

好吧,如果dateReleaseisn'在正确的格式类型中,它会抛出ParseException,但是如果有人写40/03/2010,我想得到 - 错误的日,月或年无效范围。实际上,当发送无效日期时,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验证范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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