1

GregorianCalendar在 Java 中使用,我想知道如何使用它来检查日期是否有效(例如:检查 2 月 29 日是否仅在闰年,检查日期是否不早于当前数据等)。

我创建了一个 GregorianCalendar 对象并将我想检查的数据的值传递给它,如下所示:

GregorianCalendar cal1 = new GregorianCalendar(day,month,year);

如果日期有效,我想返回 true。我怎么能这样做?

4

3 回答 3

3

基本思想:如果您尝试将无效日期设置为 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;

}
于 2012-03-17T19:19:34.620 回答
2

检查创建后,日、月、年是否仍与您传递的原始值相同。如果原始值不正确,日期将相应调整。例如。如果您通过 (29, 1, 2011) - 请注意月份值是从 0 开始的,因此 1 表示二月 - 您将返回 (1, 3, 2011)。

于 2012-03-17T19:19:05.593 回答
0
于 2018-02-15T02:52:34.827 回答