whatf
whatf

Reputation: 6458

given an offset how can i convert the current time to UTC time in javascript

a = new Date();
Sun Apr 08 2012 16:58:03 GMT+0530 (IST)

Is there any way i can get the current UTC time? I thought of getting an offset doing maths:

b = a.getTimezoneOffset()
-330

then subtract, get the value:

c = a - b
1333884483552

but again getting c as a to look is difficult. So the question: How can i get the current UTC time, in javascript?

Upvotes: 0

Views: 857

Answers (3)

pbfy0
pbfy0

Reputation: 614

You can use the toUTCString function if you need the string.

new Date().toUTCString()

Upvotes: 1

Starx
Starx

Reputation: 78991

There is a plugin called jstimezonedetect which you can use to detect the timezone. You can find it here

Or use date's UTC methods like

var now = new Date(); 
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());

Demo

Outputs

Date {Sun Apr 08 2012 18:31:50 GMT+0545 (Nepal Standard Time)}

Date {Sun Apr 08 2012 12:46:50 GMT+0545 (Nepal Standard Time)}

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340763

First of all, Date object in JavaScript is timezone-independent. It only stores the number of milliseconds since epoch. Furthermore it always uses browser time zone for toString() and get*() methods. You cannot create Date instance in a different time zone.

Thus simply use getUTC*() family of methods:

new Date().getUTCHours()
new Date().getUTCMinutes()
//...

to obtain time in UTC.

Last but not least - your code is broken. a variable represents Date and is casted to milliseconds here: c = a - b. However b is equal to a.getTimezoneOffset(). The time zone offset is in minutes. You are subtracting minutes from milliseconds...

See also

Upvotes: 3

Related Questions