frenchie
frenchie

Reputation: 52047

comparing javascript dates

I have two javascript dates and I want to know if they're the same date. The two dates can be for the same date but have different times: Date1 can be set for 3PM while Date2 can be set for 1AM.

I tried these two options but neither work:

// doesn't work when same date but different time
if (Date1.getTime() === Date2.getTime()) 

// gives true when dates are in different months
if (Date1.getUTCDate() === Date2.getUTCDate())  

What the best way to get true when Date1 and Date2 are the same day, regardless of the actual time within the day?

Thanks.

Upvotes: 3

Views: 94

Answers (4)

Chase
Chase

Reputation: 29559

Use the setHours: function on your date object and set hours, minutes, seconds and milliseconds to zero:

var today = new Date().setHours(0,0,0,0)

For your specific example, you could use:

if(date1.setHours(0,0,0,0) === date2.setHours(0,0,0,0))

where date1 and date2 are your date objects.

setHours:

Sets the hours for a specified date according to local time, and returns the number of milliseconds since 1 January 1970 00:00:00 UTC until the time represented by the updated Date instance.

EXAMPLE:

var today1 = new Date().setHours(0,0,0,0); 
var today2 = new Date().setHours(1,0,0,0); //notice the 1 here

var today3 = new Date().setHours(0,0,0,0); 
var today4 = new Date().setHours(0,0,0,0);

console.log(today1 === today2); //returns false
console.log(today3 === today4); //returns true

Upvotes: 1

Aamir
Aamir

Reputation: 5440

You can get the day, month and year of the dates and check if they are equal.

if (date1.getUTCDate() == date2.getUTCDate() && 
    date1.getUTCMonth() == date2.getUTCMonth() && 
    date1.getUTCFullYear() == date2.getUTCFullYear()) {
 // dates are on the same day
}

Upvotes: 1

J. K.
J. K.

Reputation: 8368

var equalDates = function (a, b) {
  var a_time = a.getTime();
  var b_time = b.getTime();

  var a_days = Math.floor(a_time / (24 * 3600 * 1000));
  var b_days = Math.floor(b_time / (24 * 3600 * 1000));

  return (a_days === b_days);
};

You first get the times in miliseconds. Then you round down to days (since 1970-01-01) and compare those.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 191048

Why don't you use toDateString for your comparison?

Upvotes: 1

Related Questions