4

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Parsing of non—standard strings is implemetation dependent. It's much better to manually parse strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.