setDate() set the wrong date on 31st?

后端 未结 4 1816
刺人心
刺人心 2021-01-15 04:12

This is very weird I don\'t know what I\'m doing wrong. I have a function to grab the date (i.e in this format: 06/24/2011), here\'s the function:



        
4条回答
  •  清酒与你
    2021-01-15 04:38

    JavaScript's Date objects allow you to give invalid combinations of months and days; they automagically correct those for you (so for instance, if you set the day of the month to 31 when the month is June, it automatically makes it July 1st). That means if you set the fields individually, you can run into situations where that automagic correction gets in your way.

    In your case, if you're going to set all three of those fields, you're better off using the form of the Date constructor that accepts them as arguments:

    var dt = new Date(year, month, day);
    

    (If you want hours, minutes, seconds, and milliseconds, you can add them as parameters as well.)

    So looking at your code, an off-the-cuff update:

    function checkDate(input){
        var year, month, day, d, dt;
        var dspl = input.split("/");
    
        if(dspl.length != 3)
            return NaN;
    
        year  = parseInt(dspl[2], 10);
        month = parseInt(dspl[0], 10) - 1;
        day   = parseInt(dspl[1], 10);
        if (isNaN(year) || isNaN(month) || isNaN(day)) {
            return NaN;
        }
    
        if (year < 100) {
            year += 2000;
        }
    
        d = new Date(year, month, day);
    
        var dt = jsToMsDate(d);
        return dt;
    }
    

    Some other notes on that update:

    • It's best to use parseInt to parse numbers from end users, and to always specify the radix (10 for decimal). (No, parseInt is not slower than Number or the unary + trick. People assume it is, but it isn't.)
    • No need to muck about with strings to add 2000 to years given with only two digits. But you can if you like. Note I weakened the validation there, allowing one-digit years for (say) 2001 and three-digit years for (say) 300 AD. So if you need it to be that strong, you'll need to readjust that.
    • No need to feed the date instance into new Date() again.

提交回复
热议问题