Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing dates in Javascript and timezones

When comparing dates in Javascript using <, >, =, >= and <= is the timezone used in any way in the comparison? I am hoping that the timezone is ignored.

like image 312
Sachin Kainth Avatar asked Oct 23 '14 15:10

Sachin Kainth


Video Answer


1 Answers

The timezone part of string representation of a timestamp is taken into account as you would expect, when you convert it into JavaScript Date object: the internal value is a simple scalar, normalized to UTC. So there is no need for special timezone handling when comparing Date objects:

var d1 = new Date(Date.parse("Mon, 25 Dec 1995 13:30:00 +0430"));
var d2 = new Date(Date.parse("Mon, 25 Dec 1995 13:30:00 GMT"));
print("d1:", d1);
print("d2:", d2);
if (d1<d2) {
    print("d1 is less then d2");
} else if (d1>d2) {
    print("d1 is greater then d2");
} else {
    print("d1 equals to d2");
}

which gives this output:

d1: Mon Dec 25 1995 09:00:00 GMT+0000
d2: Mon Dec 25 1995 13:30:00 GMT+0000
d1 is less then d2

[see online demo]

You'll most probably get into trouble if you compare string representations of time stamps.

like image 111
Wolf Avatar answered Sep 30 '22 09:09

Wolf