moleculezz moleculezz - 6 months ago 43
Javascript Question

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 + '\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:


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