Determining Date Equality in Javascript

JavascriptDateEquality

Javascript Problem Overview


I need to find out if two dates the user selects are the same in Javascript. The dates are passed to this function in a String ("xx/xx/xxxx").That is all the granularity I need.

Here is my code:

		var valid = true;
	var d1 = new Date($('#datein').val());
	var d2 = new Date($('#dateout').val());
	alert(d1+"\n"+d2);
	if(d1 > d2) {
		alert("Your check out date must be after your check in date.");
		valid = false;
	} else if(d1 == d2) {
		alert("You cannot check out on the same day you check in.");
		valid = false;
	}

The javascript alert after converting the dates to objects looks like this:

Tue Jan 25 2011 00:00:00 GMT-0800 (Pacific Standard Time)

Tue Jan 25 2011 00:00:00 GMT-0800 (Pacific Standard Time)

The test to determine if date 1 is greater than date 2 works. But using the == or === operators do not change valid to false.

Javascript Solutions


Solution 1 - Javascript

Use the getTime() method. It will check the numeric value of the date and it will work for both the greater than/less than checks as well as the equals checks.

EDIT:

if (d1.getTime() === d2.getTime())

Solution 2 - Javascript

If you don't want to call getTime() just try this:

(a >= b && a <= b)

Solution 3 - Javascript

var d1 = new Date($('#datein').val());
var d2 = new Date($('#dateout').val());

use two simple ways to check equality

  1. if( d1.toString() === d2.toString())
  2. if( +d1 === +d2)

Solution 4 - Javascript

var date = Wed Oct 07 2015 19:48:08 GMT+0200 (Central European Daylight Time);

var dateOne = new Date(date);
var dateTwo = new Date();

var isEqual = dateOne.getDate() === dateTwo.getDate()

this will give you the dates equality

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJarredView Question on Stackoverflow
Solution 1 - JavascriptspinonView Answer on Stackoverflow
Solution 2 - Javascriptdevmiles.comView Answer on Stackoverflow
Solution 3 - JavascriptArjun KubendranView Answer on Stackoverflow
Solution 4 - JavascriptJack VanView Answer on Stackoverflow