我在 Java 中使用 GregorianCalendar
,我想知道如何使用它来检查日期是否有效(例如:检查 2 月 29 日是否仅在闰年, 检查日期是否不早于当前数据等)。
我已经创建了一个 GregorianCalendar 对象,并将我想要检查的数据值传递给它,如下所示:
GregorianCalendar cal1 = new GregorianCalendar(day,month,year);
如果日期有效,我想返回 true。我怎么能这样做?
最佳答案
基本思想:如果您尝试将无效日期设置为 Calendar 实例,它会使它成为正确的日期,
例如,如果您将 45 设置为日期,一旦您设置和检索它就不会相同
public boolean isValid(int d, int m, int y){
//since month is 0 based
m--;
//initilizes the calendar instance, by default the current date
Calendar cal = Calendar.getInstance();
//resetting the date to the one passed
cal.set(Calendar.YEAR, y);
cal.set(Calendar.MONTH, m);
cal.set(Calendar.DATE, d);
//now check if it is the same as we set then its valid, not otherwise
if(cal.get(Calendar.DATE)==d &&cal.get(Calendar.MONTH) ==m && cal.get(Calendar.YEAR) ==y){
return true;
}
//changed so not valid
return false;
}
关于Java - 公历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9752942/