Validate number of days in a given month

前端 未结 13 2143
独厮守ぢ
独厮守ぢ 2021-01-31 18:14

Performance is of the utmost importance on this one guys... This thing needs to be lightning fast!


How would you validate the number of days in a given mont

13条回答
  •  春和景丽
    2021-01-31 18:38

    I'm mostly agreeing w/ Moayad. I'd use a table lookup, with an if check on February and the year.

    pseudocode:

    Last_Day = Last_Day_Of_Month[Month];
    Last_Day += (Month == February && Leap_Year(Year)) ? 1 : 0;
    

    Note that Leap_Year() can't be implemented simply as (Year % 4 == 0), because the rules for leap years are way more complex than that. Here's an algorithm cribbed from Wikipedia

    bool Leap_Year (int year) {
       return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
    }
    

提交回复
热议问题