From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM
and it is in UTC time. I want to convert it to the current user’s browser time using JavaScript.
How this can be done using JavaScript or jQuery?
From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM
and it is in UTC time. I want to convert it to the current user’s browser time using JavaScript.
How this can be done using JavaScript or jQuery?
Matt's answer is missing the fact that the daylight savings time could be different between Date() and the date time it needs to convert - here is my solution:
And the results in the debugger:
Using
YYYY-MM-DD hh:mm:ss
format :For converting from the
YYYY-MM-DD hh:mm:ss
format, make sure your date follow the ISO 8601 format.Important things to note
T
, a space will not work in some browsers+hh:mm
, using a string for a timezone (ex. : 'UTC') will not work in many browsers.+hh:mm
represent the offset from the UTC timezone.This is a simplified solution based on Adorjan Princ´s answer:
Usage:
@Adorojan's
answer is almost correct. But addition of offset is not correct since offset value will be negative if browser date is ahead of GMT and vice versa. Below is the solution which I came with and is working perfectly fine for me:After trying a few others posted here without good results, this seemed to work for me:
And this works to go the opposite way, from Local Date to UTC:
In Angular I used Ben's answer this way:
Edit: Angular 1.3.0 added UTC support to date filter, I haven't use it yet but it should be easier, here is the format:
Angular 1.4.3 Date API