3

I have two dates in a form:

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

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

if (dateOne == dateTwo )
    alert ("equals");
else{
    alert("not equal");
}

and even if I set up the date on client's site to Wed Oct 07 2015 19:48:08 GMT+0200 (Central European Daylight Time) I'm still getting not equal...

Even when I do this:

var data1 = new Date();
var data2 = new Date();



if (data1 == data2)
    alert ("equals");
else{
    alert("not equal");
}

The not equal appears again. What am I doing wrong?

randomuser1
  • 2,733
  • 6
  • 32
  • 68

3 Answers3

12

When you compare objects with ==, it checks to see if they are the same object, not just the same value.

You can try to get the difference between them to see if it's 0:

if (data1-data2 === 0)
    alert ("equals");
else{
    alert("not equal");
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
3

Probably they differ in miliseconds. Trim miliseconds before comparing if you don't need that precision.

date1.setMilliseconds(0); date2.setMilliseconds(0);

Maciej
  • 153
  • 9
2

Every time you call Date() you get a different date because time is passing. If you set date2 = date1, only then will they be equal. The date has a millisecond component.

kasia
  • 111
  • 4