Sachin Kainth
Sachin Kainth

Reputation: 46740

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.

Upvotes: 8

Views: 12956

Answers (1)

Wolf
Wolf

Reputation: 10238

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.

Upvotes: 10

Related Questions