下面的代码有什么问题?

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

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

我的代码:

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

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


当前回答

确保你用一个4位数的年份构造userDate作为setFullYear(10,…)!== setFullYear(2010,…)。

其他回答

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

我曾经用过这样的东西:

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

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

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

比较日期和时间:

var t1 = new Date(); // say, in ISO String =  '2022-01-21T12:30:15.422Z'
var t2 = new Date(); // say, in ISO String =  '2022-01-21T12:30:15.328Z'
var t3 = t1;

比较2个日期对象的毫秒级:

console.log(t1 === t2); // false - Bcos there is some milliseconds difference
console.log(t1 === t3); // true - Both dates have milliseconds level same values

仅根据日期比较2个日期对象(忽略任何时间差):

console.log(t1.toISOString().split('T')[0] === t2.toISOString().split('T')[0]); 
                                        // true; '2022-01-21' === '2022-01-21'

仅通过时间(ms)比较2个日期对象(忽略任何日期差异):

console.log(t1.toISOString().split('T')[1] === t3.toISOString().split('T')[1]); 
                                      // true; '12:30:15.422Z' === '12:30:15.422Z'

以上2个方法使用toISOString()方法,因此您无需担心国家之间的时区差异。

我还在学习JavaScript,我找到的唯一方法是比较两个没有时间的日期,使用Date对象的sehours方法,并将小时、分钟、秒和毫秒设置为零。然后比较这两个日期。

例如,

date1 = new Date()
date2 = new Date(2011,8,20)

Date2将小时、分钟、秒和毫秒设置为0,但date1将它们设置为date1创建的时间。要去掉date1上的小时、分钟、秒和毫秒,请执行以下步骤:

date1.setHours(0,0,0,0)

现在您可以将两个日期仅作为日期进行比较,而不必担心时间元素。

var fromdate = new Date(MM/DD/YYYY);
var todate = new Date(MM/DD/YYYY);
if (fromdate > todate){
    console.log('False');
}else{
    console.log('True');
}

如果你的日期格式不同,那么使用moment.js库转换你的日期格式,然后使用上面的代码来比较两个日期

例子:

如果您的日期是“DD/MM/YYYY”,并希望将其转换为“MM/DD/YYYY”,请参阅下面的代码示例

var newfromdate = new Date(moment(fromdate, "DD/MM/YYYY").format("MM/DD/YYYY"));
console.log(newfromdate);
var newtodate = new Date(moment(todate, "DD/MM/YYYY").format("MM/DD/YYYY"));
console.log(newtodate);

照例。太少,太迟了。

现在不鼓励使用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