Validate number of days in a given month

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

    The days of each month are known easily by exception of February for detail of leap years:

    I leave an implementation based on the algorithm that solves this problem:

    Algorithm

    if (year is not divisible by 4) then (it is a common year)
    else if (year is not divisible by 100) then (it is a leap year)
    else if (year is not divisible by 400) then (it is a common year)
    else (it is a leap year)
    
    • More info: https://en.wikipedia.org/wiki/Leap_year#Algorithm

    Implementation in Javascript

    /**
     * Doc: https://en.wikipedia.org/wiki/Leap_year#Algorithm
     * param : month is indexed: 1-12
     * param: year
     **/
    		function daysInMonth(month, year) {
    			switch (month) {
    				case 2 : //Febrary
    					if (year % 4) {
    						return 28; //common year
    					}
    					if (year % 100) {
    						return 29; //  leap year
    					}
    					
    					if (year % 400) {
    						return 28; //common year
    					}
    					return 29; //  leap year
    				case 9 : case 4 : case 6 : case 11 :
    					return 30;
    				default :
    					return 31
    			}
    		}
        
        /** Testing daysInMonth Function **/
        $('#month').change(function() {
            var mVal = parseInt($(this).val());
            var yVal = parseInt($('#year').val());
            $('#result').text(daysInMonth(mVal, yVal));
        });
        
    
    
    
    
    
    
    
    

    days:

提交回复
热议问题