简体   繁体   English

Java检查日期(由整数组成)是否有效

[英]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日作为输出的原因:

  • when you set the month as month-1, in this case you're setting the month as June, because the month parameter in the calendar.set() method is 0-based (January has the index 0) 当您将月份设置为month-1时,在这种情况下,您将月份设置为June,因为calendar.set()方法中的month参数是基于0的(January的索引为0)
  • June has 30 calendar days, so if you set the day as 31, it will overflow into July 1st; 6月有30个日历日,因此,如果将日期设置为31,它将溢出到7月1日。 if you would've set 44 as the number of days, the output would be 14th of July 2014 如果您将天数设置为44,则输出为2014年7月14日

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM