修改日期方法

时间:2013-10-15 03:27:08

标签: java

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

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

  • 正确没有。每月的几天
  • 任何月份都不应该只允许31天
  • 如果年份是闰年,则返回true

代码:

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); 
}

1 个答案:

答案 0 :(得分:1)

您可以尝试使用Calendar API ...

例如......

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 ...