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.
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.
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.
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 ...
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.
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())
If you don't want to call getTime()
just try this:
(a >= b && a <= b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With