Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

javascript - 仅比较日期部分,而不比较JavaScript中的时间(Comparing date part only without comparing time in 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.(顺便说一句,当我在警报中显示两个日期时,它们显示为完全相同。)

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

Is there a simpler way to compare dates and not including the time?(有没有比较日期而不包括时间的简单方法?)

  ask by moleculezz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.(我仍在学习JavaScript,而我发现唯一可以比较两个没有时间的日期的方法是使用Date对象的setHours方法并将小时,分钟,秒和毫秒设置为零。)

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.(将date2小时,分钟,秒和毫秒设置为零,但date1会将其设置为创建date1的时间。)

To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:(要摆脱date1的小时,分??钟,秒和毫秒,请执行以下操作:)
date1.setHours(0,0,0,0)

Now you can compare the two dates as DATES only without worrying about time elements.(现在,您可以仅将两个日期作为“日期”进行比较,而不必担心时间元素。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...