0

I have two dates :

date1 = "2013-07-08 12:30:00"

date2 = "2013-07-08 13:30:00"

Now in javascript i want to match these two dates and its they dont match than i want to delete the appointment and if they match than nothing to do.

I tried this code but its not working :

  if(date1 == date2)// Event already exists
  {
      // do nothing
  }
  else
  {
      // delete the record.
  }

I tried to compare with "new Date(date1) == new Date(date2)" also but its not working either.

There is some problem in my code or date format. can anyone know how to do this and where i am wrong in this code ?

Thanks in advance.

Mausami
  • 692
  • 1
  • 13
  • 24

3 Answers3

1

Two different objects are never the same, you have to compare the numbers that make up the unix timestamp:

var date1 = "2013-07-08 12:30:00",
    date2 = "2013-07-08 13:30:00";

var d1 = new Date(date1);
var d2 = new Date(date2);

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

}

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

it works for me:

var date1 = "2013-07-08 12:30:00";

var date2 = "2013-07-08 12:30:00";
var date3 = "2013-07-08 12:00:00";

console.log(date1 == date2); //true
console.log(date1 == date3); //false

Jsfiddle link

Gyandeep
  • 12,726
  • 4
  • 31
  • 42
  • Naming your variables date doesn't make them date objects. When comparing primative types you should use === – HMR Jul 10 '13 at 00:57
  • Please change the names of variables according to your choice and also use ===, now check if it gives you the answer or not. please use the fiddle link i have provided – Gyandeep Jul 10 '13 at 01:54
0

Adeno has a valid answer but will fail if the dates are milliseconds appart (not the case in OP's example if you use a valid date string). To be sure you're comparing dates by minutes or days you can do:

function sameTime(dt1,dt2){
  //round the dates to the minutes
  var t1=new Date(dt1);
  var t2=new Date(dt2);
  t1.setSeconds(0,0);
  t2.setSeconds(0,0);
  return t1.toString()===t2.toString();
}
function sameDay(dt1,dt2){
  //round the dates to the day
  var t1=new Date(dt1);
  var t2=new Date(dt2);
  t1.setHours(0,0,0,0);
  t2.setHours(0,0,0,0);
  return t1.toString()===t2.toString();
}
function sameMonth(dt1,dt2){
  //round the dates to the month
  var t1=new Date(dt1);
  var t2=new Date(dt2);
  t1.setHours(0,0,0,0);
  t2.setHours(0,0,0,0);
  t1.setDate(1);
  t2.setDate(1);
  return t1.toString()===t2.toString();
}
var date1 = "2013-07-08T12:30:00",
    date2 = "2013-07-08T13:30:00";
var d1 = new Date(date1);
var d2 = new Date(date2);

console.log(sameTime(d1,d2));//precise to the minute
console.log(sameDay(d1,d2));//precise to the day
console.log(sameMonth(d1,d2));//precise to the month
HMR
  • 37,593
  • 24
  • 91
  • 160