Categories
Uncategorized

Handling Date objects in Javascript

Handling date objects in javascript can be very tricky at times. Here are few tricky scenarios.

Comparision with ‘===’

When you compare two date objects that contain the exact same time stamp using ‘===’, then this will not be true as two objects can only be equal if they refer to the same object.

var date1 = new Date('2017-05-19T01:56:09.218Z');
var date2 = new Date('2017-05-19T01:56:09.218Z');

if(date1===date2) 
   console.log('yes');
else 
   console.log('no');

Output

no

Demo

The solution to this, is to convert this to some other format like date.getTime() or date.getISOString(), etc. Here is the example implementation of that.

var date1 = new Date('2017-05-17T14:48:12.000Z');
var date2 = new Date('2017-05-17T14:48:12.000Z');
if (date1.toISOString() === date2.toISOString()) {
 console.log('yes');
}

Output

yes

Demo

Copying a Date Object

When you try to copy date objects like the following example, then both the variables refer to the same date objects and whatever changes you make on either of them reflects on the other, which is not the required outcome

var date1 = new Date('2017-05-17T14:48:12.000Z');
var date2 = date1;
date1.setHours(5, 30, 0, 0);
console.log(date2);
console.log(date1);

Output

Wed May 17 2017 05:30:00 GMT-0400 (Eastern Daylight Time)
Wed May 17 2017 05:30:00 GMT-0400 (Eastern Daylight Time)

Demo

To solve this we need to create a new Date object while assigning the date to a new variable.

var date1 = new Date('2017-05-17T14:48:12.000Z');
var date2 = new Date(date1);
date1.setHours(5, 30, 0, 0);
console.log(date2);
console.log(date1);

Output

Wed May 17 2017 10:48:12 GMT-0400 (Eastern Daylight Time)
Wed May 17 2017 05:30:00 GMT-0400 (Eastern Daylight Time)

Demo