且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在java中检查日期

更新时间:2022-06-01 07:12:59

目前的方式是使用日历类。它具有 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");
}