[英]Java Check whether Date (made of integers) is valid
I am currently setting a Date
using the following function. 我目前正在使用以下功能设置
Date
。
private Date getDate (int day, int month, int year){
Calendar calendar = Calendar.getInstance();
calendar.set(year, month-1, day);
Date date = calendar.getTime();
return date;
}
However if (31, 6, 2014) is entered, the date is simply changed to the 1st of July 2014. Is there a way that I could check whether a date is valid if my input is as above? 但是,如果输入(2014年6月31日),则日期仅更改为2014年7月1日。如果我的输入如上所述,是否可以检查日期是否有效?
Thanks for your help. 谢谢你的帮助。
Reason why you get 1st of July 2014 as output: 您得到2014年7月1日作为输出的原因:
To counteract this, set lenient to false: 要解决此问题,请将lenient设置为false:
calendar.setLenient(false);
and an exception will be thrown if the dates are out of bounds 如果日期超出范围,则会引发异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.