下面的代码有什么问题?

也许只比较日期而不是时间会更简单。我也不确定如何做到这一点,我搜索了一下,但我找不到我的确切问题。

顺便说一句,当我在警报中显示这两个日期时,它们显示完全相同。

我的代码:

window.addEvent('domready', function() {
    var now = new Date();
    var input = $('datum').getValue();
    var dateArray = input.split('/');
    var userMonth = parseInt(dateArray[1])-1;
    var userDate = new Date();
    userDate.setFullYear(dateArray[2], userMonth, dateArray[0], now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());

    if (userDate > now)
    {
        alert(now + '\n' + userDate);
    }
});

有没有一种更简单的方法来比较日期而不包括时间?


当前回答

这可能是一个更简洁的版本,还请注意,在使用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);
    }
});

检查MDC parseInt页面以获得关于基数的更多信息。

JSLint是一个很好的工具,可以捕捉诸如缺少基数之类的东西,以及许多其他可能导致模糊和难以调试的错误的东西。它迫使您使用更好的编码标准,以避免将来的麻烦。我在编写的每个JavaScript项目中都使用它。

其他回答

我是这样做的:

var myDate  = new Date($('input[name=frequency_start]').val()).setHours(0,0,0,0);
var today   = new Date().setHours(0,0,0,0);
if(today>myDate){
    jAlert('Please Enter a date in the future','Date Start Error', function(){
        $('input[name=frequency_start]').focus().select();
    });
}

我最终使用的一个选项是使用Moment.js的diff函数。通过调用start之类的函数。Diff(以“天”结尾)你可以用天数的整数来比较差异。

使用javascript,您可以将现有日期对象的时间值设置为零,然后解析回日期。解析回Date后,两者的Time值都为0,您可以进行进一步的比较

      let firstDate = new Date(mydate1.setHours(0, 0, 0, 0));
      let secondDate = new Date(mydate2.setHours(0, 0, 0, 0));

      if (selectedDate == currentDate)
      {
        console.log('same date');
      }
      else
      {
        console.log(`not same date`);
      }

date.js库对于这些事情很方便。它使所有与JS日期相关的脚本编写变得容易得多。

对我有用: 我需要比较一个日期和一个本地dateRange

let dateToCompare = new Date().toLocaleDateString().split("T")[0])
let compareTime = new Date(dateToCompare).getTime()

let startDate = new Date().toLocaleDateString().split("T")[0])
let startTime = new Date(startDate).getTime()

let endDate = new Date().toLocaleDateString().split("T")[0])
let endTime = new Date(endDate).getTime()

return compareTime >= startTime && compareTime <= endTime