下面的代码有什么问题?

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

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

我的代码:

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);
    }
});

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


当前回答

照例。太少,太迟了。

现在不鼓励使用momentjs(他们说的,不是我说的),首选是dayjs。

可以使用dayjs的isSame。

https://day.js.org/docs/en/query/is-same

dayjs().isSame('2011-01-01', 'date')

你还可以使用其他一些单位进行比较: https://day.js.org/docs/en/manipulate/start-of#list-of-all-available-units

其他回答

在看到这个问题的同时,我决定发布另一个解决方案,因为我觉得它不太令人满意,至少对我的需求来说:

我曾经用过这样的东西:

var currentDate= new Date().setHours(0,0,0,0);

var startDay = new Date(currentDate - 86400000 * 2);
var finalDay = new Date(currentDate + 86400000 * 2);

这样,我就可以用我想要的格式来处理这些日期。但这只是为了我的需要,但我还是决定张贴它,也许它会帮助到别人

在两个日期上都使用toDateString()即可。toDateString不包括时间,因此对于同一日期的两次,值将相等,如下所示。

var d1 = new Date(2019,01,01,1,20)
var d2 = new Date(2019,01,01,2,20)
console.log(d1==d2) // false
console.log(d1.toDateString() == d2.toDateString()) // true

显然,在这个问题上其他地方表达的一些关于时区的担忧是有效的,但在许多情况下,这些是不相关的。

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

照例。太少,太迟了。

现在不鼓励使用momentjs(他们说的,不是我说的),首选是dayjs。

可以使用dayjs的isSame。

https://day.js.org/docs/en/query/is-same

dayjs().isSame('2011-01-01', 'date')

你还可以使用其他一些单位进行比较: https://day.js.org/docs/en/manipulate/start-of#list-of-all-available-units

我是这样做的:

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();
    });
}