April 8, 2012

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

Question by whatf

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?

Answer by Starx

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)}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!