Validate number of days in a given month

前端 未结 13 2355
独厮守ぢ
独厮守ぢ 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:34

    This will not perform as well as the accepted answer. I threw this in here because I think it is the simplest code. Most people would not need to optimize this function.

    function validateDaysInMonth(year, month, day)
    {
        if (day < 1 || day > 31 || (new Date(year, month, day)).getMonth() != month)
            throw new Error("Frack!");
    }
    

    It takes advantage of the fact that the javascript Date constructor will perform date arithmetic on dates that are out of range, e.g., if you do:

    var year = 2001; //not a leap year!
    var month = 1 //February
    var day = 29; //not a valid date for this year
    new Date(year, month, day);
    

    the object will return Mar 1st, 2001 as the date.

提交回复
热议问题