Convert UTC date time to local date time

2018-12-31 06:09发布

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?

23条回答
怪性笑人.
2楼-- · 2018-12-31 06:41

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.

var utcDate = '2011-06-29T16:52:48.000Z';  // ISO-8601 formatted date returned from server
var localDate = new Date(utcDate);

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.

查看更多
梦醉为红颜
3楼-- · 2018-12-31 06:42
function getUTC(str) {
    var arr = str.split(/[- :]/);
    var utc = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
    utc.setTime(utc.getTime() - utc.getTimezoneOffset()*60*1000)
    return utc;
}

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.

查看更多
不流泪的眼
4楼-- · 2018-12-31 06:44

You should get the (UTC) offset (in minutes) of the client:

var offset = new Date().getTimezoneOffset();

And then do the correspondent adding or substraction to the time you get from the server.

Hope this helps.

查看更多
只若初见
5楼-- · 2018-12-31 06:46

Add the time zone at the end, in this case 'UTC':

theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));

after that, use toLocale()* function families to display the date in the correct locale

theDate.toLocaleString();  // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString();  // "9:52:48 AM"
theDate.toLocaleDateString();  // "6/29/2011"
查看更多
低头抚发
6楼-- · 2018-12-31 06:49

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.

moment().format('MMMM Do YYYY, h:mm:ss a'); // September 14th 2018, 12:51:03 pm
moment().format('ffffdd');                    // Friday
moment().format("MMM Do YY"); 

For more details you can refer Moment js website

查看更多
长期被迫恋爱
7楼-- · 2018-12-31 06:52

Append 'UTC' to the string before converting it to a date in javascript:

var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
查看更多
登录 后发表回答