Jimmy Beaner
Jimmy Beaner

Reputation: 41

Javascript UTC timestamp to Local Timezone

I'm trying to convert a timestamp being returned from a JSON resource in javascript that is displaying in UTC to the users local timezone. Below i'm trying to adjust with the user offset.

Example UTC output for date: Tue Mar 27 2012 02:29:15 GMT-0400 (EDT)

Code

var date = new Date(data.date_created); //Data.date_created coming from json payload
var offset = date.getTimezoneOffset() //Get offset
var new_date = new Date(date  offset); //Add offset to userdate

I'm struggling with the appropriate method to achieve this. Can anyone point me in the right direction?

Upvotes: 4

Views: 3569

Answers (1)

neniu
neniu

Reputation: 419

I might be missing something but

var date = new Date( data.date_created );

does what I think you want.

>>> d=new Date('Tue Mar 27 2012 02:29:15 GMT-0800')
Date {Tue Mar 27 2012 06:29:15 GMT-0400 (EDT)}
>>> d.toLocaleString()
"Tue Mar 27 06:29:15 2012"
>>> d=new Date('Tue Mar 27 2012 02:29:15 GMT+0300')
Date {Mon Mar 26 2012 19:29:15 GMT-0400 (EDT)}
>>> d.toLocaleString()
"Mon Mar 26 19:29:15 2012"

Note how changing the GMT offset from -8 to +3 changes the resulting time by 11 hours.

Upvotes: 5

Related Questions