Comparing date part only without comparing time in JavaScript

后端 未结 22 1675
春和景丽
春和景丽 2020-11-22 10:59

What is wrong with the code below?

Maybe it would be simpler to just compare date and not time. I am not sure how to do this either, and I searched, but I couldn\'t

22条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 11:53

    This might be a little cleaner version, also note that you should always use a radix when using parseInt.

    window.addEvent('domready', function() {
        // Create a Date object set to midnight on today's date
        var today = new Date((new Date()).setHours(0, 0, 0, 0)),
        input = $('datum').getValue(),
        dateArray = input.split('/'),
        // Always specify a radix with parseInt(), setting the radix to 10 ensures that
        // the number is interpreted as a decimal.  It is particularly important with
        // dates, if the user had entered '09' for the month and you don't use a
        // radix '09' is interpreted as an octal number and parseInt would return 0, not 9!
        userMonth = parseInt(dateArray[1], 10) - 1,
        // Create a Date object set to midnight on the day the user specified
        userDate = new Date(dateArray[2], userMonth, dateArray[0], 0, 0, 0, 0);
    
        // Convert date objects to milliseconds and compare
        if(userDate.getTime() > today.getTime())
        {
                alert(today+'\n'+userDate);
        }
    });
    

    Checkout the MDC parseInt page for more information about the radix.

    JSLint is a great tool for catching things like a missing radix and many other things that can cause obscure and hard to debug errors. It forces you to use better coding standards so you avoid future headaches. I use it on every JavaScript project I code.

提交回复
热议问题