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

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

问题描述

下面的代码有什么问题?



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



BTW,当我在一个警报显示两个日期,它们显示完全相同。



我的代码:

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

有比较简单的方法来比较日期,不包括时间吗?

解决方案

我仍然在学习JavaScript,我发现的唯一的方法,对我来比较两个日期没有时间是使用 setHours 方法,并将小时,分钟,秒和毫秒设置为零。



例如,

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

date2 将设置为小时,分钟,秒和毫秒为零,但date1将设置为date1创建的时间。要清除date1上的小时,分​​钟,秒和毫秒,请执行以下操作:

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

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

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.

My code:

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

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

解决方案

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.

For example,

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

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)

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

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

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