Convert UTC date time to local date time

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

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?

回答1:

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)" 


回答2:

This is an universal solution:

function convertUTCDateToLocalDate(date) {     var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);      var offset = date.getTimezoneOffset() / 60;     var hours = date.getHours();      newDate.setHours(hours - offset);      return newDate;    } 

Usage:

var date = convertUTCDateToLocalDate(new Date(date_string_you_received)); 

Display the date based on the client local setting:

date.toLocaleString(); 


回答3:

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.



回答4:

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:

Put this function in your head:

 

Then generate the following for each date in the body of your page:

 

To remove the GMT and time zone, change the following line:

document.write(d.toString().replace(/GMT.*/g,"")); 


回答6:

function convertUTCDateToLocalDate(date) {     var newDate = new Date(date);     newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset());     return newDate; } 

Usage:

var date = convertUTCDateToLocalDate(new Date(date_string_you_received)); 


回答7:

After trying a few others posted here without good results, this seemed to work for me:

convertUTCDateToLocalDate: function (date) {     return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(),  date.getHours(), date.getMinutes(), date.getSeconds())); } 

And this works to go the opposite way, from Local Date to UTC:

convertLocalDatetoUTCDate: function(date){     return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); } 


回答8:

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:

    function ConvertUTCTimeToLocalTime(UTCDateString)     {         var convertdLocalTime = new Date(UTCDateString);          var hourOffset = convertdLocalTime.getTimezoneOffset() / 60;          convertdLocalTime.setHours( convertdLocalTime.getHours() + hourOffset );           return convertdLocalTime;     } 

And the results in the debugger:

UTCDateString: "2014-02-26T00:00:00" convertdLocalTime: Wed Feb 26 2014 00:00:00 GMT-0800 (Pacific Standard Time) 


回答9:

Use this for UTC and Local time convert and vice versa.

//Covert datetime by GMT offset  //If toUTC is true then return UTC time other wise return local time function convertLocalDateToUTCDate(date, toUTC) {     date = new Date(date);     //Local time converted to UTC     console.log("Time: " + date);     var localOffset = date.getTimezoneOffset() * 60000;     var localTime = date.getTime();     if (toUTC) {         date = localTime + localOffset;     } else {         date = localTime - localOffset;     }     date = new Date(date);     console.log("Converted time: " + date);     return date; } 


回答10:

To me the simplest seemed using

datetime.setUTCHours(datetime.getHours()); datetime.setUTCMinutes(datetime.getMinutes()); 

(i thought the first line could be enough but there are timezones which are off in fractions of hours)



回答11:

A JSON date string (serialized in C#) looks like "2015-10-13T18:58:17".

In angular, (following Hulvej) make a localdate filter:

myFilters.filter('localdate', function () {     return function(input) {         var date = new Date(input + '.000Z');         return date;     }; }) 

Then, display local time like:

{{order.createDate | localdate | date : 'MMM d, y h:mm a' }} 


回答12:

In case you don't mind usingmoment.js and your time is in UTC just use the following:

moment.utc('6/29/2011 4:52:48 PM').toDate(); 

if your time is not in utc but any other locale known to you, then use following:

moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY', 'fr').toDate(); 

if your time is already in local, then use following:

moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY'); 


回答13:

I Answering This If Any one want function that display converted time to specific id element and apply date format string yyyy-mm-dd here date1 is string and ids is id of element that time going to display.

function convertUTCDateToLocalDate(date1, ids)  {   var newDate = new Date();   var ary = date1.split(" ");   var ary2 = ary[0].split("-");   var ary1 = ary[1].split(":");   var month_short = Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');   newDate.setUTCHours(parseInt(ary1[0]));   newDate.setUTCMinutes(ary1[1]);   newDate.setUTCSeconds(ary1[2]);   newDate.setUTCFullYear(ary2[0]);   newDate.setUTCMonth(ary2[1]);   newDate.setUTCDate(ary2[2]);   ids = document.getElementById(ids);   ids.innerHTML = " " + newDate.getDate() + "-" + month_short[newDate.getMonth() - 1] + "-" + newDate.getFullYear() + " " + newDate.getHours() + ":" + newDate.getMinutes() + ":" + newDate.getSeconds();             } 

i know that answer has been already accepted but i get here cause of google and i did solve with getting inspiration from accepted answer so i did want to just share it if someone need.



回答14:

Based on @digitalbath answer, here is a small function to grab the UTC timestamp and display the local time in a given DOM element (using jQuery for this last part):

https://jsfiddle.net/moriz/6ktb4sv8/1/



回答15:

Using YYYY-MM-DD hh:mm:ss format :

var date = new Date('2011-06-29T16:52:48+00:00'); date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)" 

For converting from the YYYY-MM-DD hh:mm:ss format, make sure your date follow the ISO 8601 format.

Year:      YYYY (eg 1997)     Year and month:      YYYY-MM (eg 1997-07) Complete date:      YYYY-MM-DD (eg 1997-07-16) Complete date plus hours and minutes:     YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)     Complete date plus   hours, minutes and seconds:     YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)     Complete date plus hours, minutes, seconds and a decimal fraction of a second     YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where:  YYYY = four-digit year MM   = two-digit month (01=January, etc.) DD   = two-digit day of month (01 through 31) hh   = two digits of hour (00 through 23) (am/pm NOT allowed) mm   = two digits of minute (00 through 59) ss   = two digits of second (00 through 59) s    = one or more digits representing a decimal fraction of a second TZD  = time zone designator (Z or +hh:mm or -hh:mm) 

Important things to note

  1. You must separate the date and the time by a T, a space will not work in some browsers
  2. You must set the timezone using this format +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.


回答16:

This works for me:

function convertUTCDateToLocalDate(date) {     var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);     return newDate;    } 


回答17:

I wrote a nice little script that takes a UTC epoch and converts it the client system timezone and returns it in d/m/Y H:i:s (like the PHP date function) format:

getTimezoneDate = function ( e ) {      function p(s) { return (s 


回答18:

For me above solutions didn't work.

With IE the UTC date-time conversion to local is little tricky. For me, the date-time from web API is '2018-02-15T05:37:26.007' and I wanted to convert as per local timezone so I used below code in JavaScript.

var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z'); 


回答19:

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.



回答20:

In Angular I used Ben's answer this way:

$scope.convert = function (thedate) {     var tempstr = thedate.toString();     var newstr = tempstr.toString().replace(/GMT.*/g, "");     newstr = newstr + " UTC";     return new Date(newstr); }; 

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:

{{ date_expression | date : format : timezone}} 

Angular 1.4.3 Date API



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!