简体   繁体   中英

Convert UTC Date to Local Date in JavaScript

I am getting a set of JSON results back from a server. Each result has a property called CreatedOn . I peaked at the value of CreatedOn using the following code:

var results = getResultsFromServer();
for (var i=0; i<results.length; i++) {
  console.log(results[i].CreatedOn);
}

This code prints out values like the following:

2014-10-23T17:15:55.624
2014-10-22T16:13:55.342
2013-12-21T12:26:55.912

My question is, how do I convert those values to local time in JavaScript? For instance, what about the following:

var results = getResultsFromServer();
for (var i=0; i<results.length; i++) {
  var utc = results[i].CreatedOn;
  var local = ?;

  console.log('UTC: ' + utc + ' Local: ' + local);
}

Thank you for your help.

Just do this

var results = getResultsFromServer();
for (var i=0; i<results.length; i++) {
  var utc = results[i].CreatedOn;
  var local = new Date(utc);

  console.log('UTC: ' + utc + ' Local: ' + local);
}

Console:

var date = new Date('2014-10-23T17:15:55.624')
date
Thu Oct 23 2014 12:15:55 GMT-0500 (Central Daylight Time)

You should use

var local = utc.toLocaleString();

More information at

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM