Here is my javascript code:
var prevDate = new Date('1/25/2011'); // the string contains a date which
// comes from a server-side script
// may/may not be the same as current date
var currDate = new Date(); // this variable contains current date
currDate.setHours(0, 0, 0, 0); // the time portion is zeroed-out
console.log(prevDate); // Tue Jan 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
console.log(currDate); // Tue Jan 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
console.log(prevDate == currDate); // false -- why oh why
Notice that both dates are the same but comparing using ==
indicates they are not the same. Why?
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.
For comparing the two dates, we have used the compareTo() method. If both dates are equal it prints Both dates are equal. If date1 is greater than date2, it prints Date 1 comes after Date 2.
To compare two dates, you can use either toString() or valueOf() . The toString() method converts the date into an ISO date string, and the valueOf() method converts the date into milliseconds since the epoch.
I don't think you can use ==
to compare dates in JavaScript. This is because they are two different objects, so they are not "object-equal". JavaScript lets you compare strings and numbers using ==
, but all other types are compared as objects.
That is:
var foo = "asdf";
var bar = "asdf";
console.log(foo == bar); //prints true
foo = new Date();
bar = new Date(foo);
console.log(foo == bar); //prints false
foo = bar;
console.log(foo == bar); //prints true
However, you can use the getTime
method to get comparable numeric values:
foo = new Date();
bar = new Date(foo);
console.log(foo.getTime() == bar.getTime()); //prints true
Dont use == operator to compare object directly because == will return true only if both compared variable is point to the same object, use object valueOf() function first to get object value then compare them i.e
var prevDate = new Date('1/25/2011');
var currDate = new Date('1/25/2011');
console.log(prevDate == currDate ); //print false
currDate = prevDate;
console.log(prevDate == currDate ); //print true
var currDate = new Date(); //this contain current date i.e 1/25/2011
currDate.setHours(0, 0, 0, 0);
console.log(prevDate == currDate); //print false
console.log(prevDate.valueOf() == currDate.valueOf()); //print true
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