Validate number of days in a given month

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

    I've been doing this using the Date object (assuming it's compiled, and hence blindingly fast compared to scripting).

    The trick is that if you enter a too high number for the date part, the Date object wraps over into the next month. So:

    var year = 2009;
    var month = 1;
    var date = 29;
    
    var presumedDate = new Date(year, month, date);
    
    if (presumedDate.getDate() != date)
        WScript.Echo("Invalid date");
    else
        WScript.Echo("Valid date");
    

    This will echo "Invalid date" because presumedDate is actually March 1st.

    This leaves all the trouble of leap years etc to the Date object, where I don't have to worry about it.

    Neat trick, eh? Dirty, but that's scripting for you...

提交回复
热议问题