0

我有这段代码,我需要一个更好的方法版本。

这个更好的版本应该有ff:

  • 正确的没有。每个月的天数
  • 不应该只允许任何一个月的 31 天
  • 如果年份是闰年则返回真

代码:

private boolean dateCorrect(int monthNum, int dayNum, int yearNum)
{
if ( (monthNum >=1) && (monthNum <=12) &&
         (dayNum >= 1) && (dayNum <=31) &&
         (yearNum >=1000) && (yearNum <= 9999)
          return false;

switch (monthNum)
        {
        case 1:
        if (leapYear(yearInt))
            return (dayNum >= 1) && (dayNum <=29);
        else
            return (dayNum >=1) && (dayNum <=28);
        case 2:
            return (dayNum >=1) && (dayNum <=31);
        case 3:
             return (dayNum >=1) && (dayNum <=30);
        case 4:
             return (dayNum >=1) && (dayNum <=31);
        case 5:
            return (dayNum >=1) && (dayNum <=30);
        case 6:
            return (dayNum >=1) && (dayNum <=31);
        case 7:
            return (dayNum >=1) && (dayNum <=30);
        case 8:
            return (dayNum >=1) && (dayNum <=31);
        case 9:
            return (dayNum >=1) && (dayNum <=30);
        case 10:
            return (dayNum >=1) && (dayNum <=31);
        case 11:
            return (dayNum >=1) && (dayNum <=30);
        case 12:
            return (dayNum >=1) && (dayNum <=31);
       }
   }
}

private boolean leapYear( int yearNum)
{ 
       return (( yearNum % 4 == 0) && ( yearNum % 100 != 0)) 
        || ( yearNum % 400 == 0); 
}
4

1 回答 1

1

您可以尝试使用CalendarAPI​​ ...

例如...

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(yearNum, monthNum - 1, dayNum);

return dayNum == cal.get(Calendar.DATE) && 
    (monthNum - 1) == cal.get(Calendar.MONTH) &&
    yearNum == cal.get(Calendar.YEAR) && (year % 400) == 0;

true如果日期的各个部分有效并且年份是闰年,这将返回...

于 2013-10-15T03:36:12.713 回答