Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining Date Equality in Javascript

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.

like image 296
Jarred Avatar asked Jan 03 '11 18:01

Jarred


People also ask

How do you find the date equality?

The equality operator checks for reference equality. This means it only returns true if the two variables refer the the same object. If you create two Date objects ( var a = new Date(); var b = new Date(); ), they will never be equal.

Can you compare JavaScript dates?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.

Why does JavaScript use === instead of ==?

Use === if you want to compare couple of things in JavaScript, it's called strict equality, it means this will return true if only both type and value are the same, so there wouldn't be any unwanted type correction for you, if you using == , you basically don't care about the type and in many cases you could face ...

Is equal method in JavaScript?

equals() method is used to compare two buffer objects and returns True of both buffer objects are the same otherwise returns False. Parameters: This method accepts single parameter otherBuffer which holds the another buffer to compare with buffer object.


2 Answers

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()) 
like image 158
spinon Avatar answered Oct 06 '22 01:10

spinon


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

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

like image 41
devmiles.com Avatar answered Oct 06 '22 00:10

devmiles.com