問題描述
我覺得奇怪的是,在 Java 中創建 Date
對象的最明顯方法已被棄用,并且似乎已被不那么明顯的寬松日歷取代".
I find it curious that the most obvious way to create Date
objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.
您如何檢查以日、月和年的組合形式給出的日期是否有效?
How do you check that a date, given as a combination of day, month, and year, is a valid date?
例如,2008-02-31(如 yyyy-mm-dd)將是一個無效的日期.
For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.
推薦答案
目前的方式是使用日歷類.它有 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");
}
這篇關于如何在 Java 中健全地檢查日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!