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?
In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format.
More info here:
IN this case the server would return
'2011-06-29T16:52:48.000Z'
which would feed directly into the JS Date object.The
localDate
will be in the right local time which in my case would be two hours later (DK time).You really don't have to do all this parsing which just complicates stuff, as long as you are consistent with what format to expect from the server.
For others who visit - use this function to get a Local date object from a UTC string, should take care of DST and will work on IE, IPhone etc.
We split the string (Since JS Date parsing is not supported on some browsers) We get difference from UTC and subtract it from the UTC time, which gives us local time. Since offset returned is calculated with DST (correct me if I am wrong), so it will set that time back in the variable "utc". Finally return the date object.
You should get the (UTC) offset (in minutes) of the client:
And then do the correspondent adding or substraction to the time you get from the server.
Hope this helps.
Add the time zone at the end, in this case 'UTC':
after that, use toLocale()* function families to display the date in the correct locale
You can use momentjs ,
moment(date).format()
will always give result in local date.Bonus , you can format in any way you want. For eg.
For more details you can refer Moment js website
Append 'UTC' to the string before converting it to a date in javascript: