简体   繁体   中英

Javascript: how to convert a UTC date to local one?

Looks like a very simple thing to do? Not afrer reading this http://dygraphs.com/date-formats.html - what a mess!

var time_utc="2016-04-25 20:19:00.306671";
document.write("Local date:"+new Date(time_utc+" UTC")); // Firefox 44.0.2: Invalid Date 

How do I print a date in above format adjusted to local time?

Have you looked into Moment.js? http://momentjs.com/ It's a handy date-object wrapper that makes date object manipulation easy. Particularly, the local() function provided will give you what you need here.

All you have to do is install moment from npm and then include it in your js file at the top like this:

var moment = require("moment");

Then to change your time_utc variable to local all you have to do is:

var time_utc="2016-04-25 20:19:00.307";
document.write("Local date:"+moment(time_utc).local());

As someone advised me before, it is not wise to include an entire library for a simple, one time function. As a disclaimer, my work requires me to do many date-time calculations and conversions throughout a large project, so including a library for ease is much preferred in my case. However, if you only have to use it this one time, my answer may not be the best.

You need append UTC to the string before converting it to a local date in js:

var date = new Date('25/04/2016 4:52:48 PM UTC');
date.toString() // "Mon Apr 25 2016 09:52:48 GMT-0700 (PDT)"

The article you provided mentions halfway through the page,

Using hyphens (-) instead of slashes (/) works in WebKit browsers, but not in IE or FF. Beware the UTC parse of YYYY-MM-DD!

As well as,

Don't try to specify milliseconds. Only recent versions of Chrome will understand you.

With the date 2016-04-25 20:19:00.306671 you use hyphens and milliseconds. You could modify your time_utc string a bit to make it compatible like so,

var time_utc = "2016-04-25 20:19:00.306671";
time_utc = time_utc.replace(/-/g, "/"); 
time_utc = time_utc.split(".").shift();

var d = new Date(time_utc);
d.toString();

The above code outputs,

Mon Apr 25 2016 20:19:00 GMT+0200 (CEST)

If you use moment.js , you can use:

var time_utc = "2016-04-25 20:19:00.306671";

var localDate = moment.utc(time_utc).local();

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