仅比较日期部分而不比较 JavaScript 中的时间 [英] Comparing date part only without comparing time in JavaScript

查看:25
本文介绍了仅比较日期部分而不比较 JavaScript 中的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码有什么问题?

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 find my exact problem.

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

BTW, when I display the two dates in an alert, they show as exactly the same.

我的代码:

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 + '
' + userDate);
    }
});

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

Is there a simpler way to compare dates and not including the time?

推荐答案

我仍在学习 JavaScript,我发现的唯一一种可以在没有时间的情况下比较两个日期的方法是使用 setHours 方法并将小时、分钟、秒和毫秒设置为零.然后比较两个日期.

I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.

例如

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

date2 会将小时、分钟、秒和毫秒设置为零,但 date1 会将它们设置为 date1 的创建时间.要去除 date1 上的小时、分钟、秒和毫秒,请执行以下操作:

date2 will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:

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

现在您可以将两个日期作为 DATES 进行比较,而无需担心时间元素.

Now you can compare the two dates as DATES only without worrying about time elements.

这篇关于仅比较日期部分而不比较 JavaScript 中的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆