简体   繁体   中英

Convert UTC to standard date time format using javascript

How can I convert a UTC time into proper date - time format using Javascript?

This is what I want to do

var d = new Date("2014-01-01");
var new_d = d.toUTC(); // 1388534400000
var old_d = function(new_d){
    // return "2014-01-01" // how can i get this? 
}

Now How, can i get orignal date - 2014-01-01 from 1388534400000?

****Also, Please note that when i do this --- new Date(1388534400000); it gives date 1 day less. That is, instead of giving Jan 01 2014 , it gives Dec 31 2013 . But, I want Jan 01 2014.****

Is there any method to do the opposite of toUTC() method?

// _________ For those whose toUTC() doesnt work

"toUTC" method works in console of my chrome See screen shot below

在此处输入图片说明

When you pass a string containing hyphens to the Date constructor, it will treat that as UTC. And if you don't pass a time, it will consider it to be midnight. If you are in a time zone that is behind UTC (such as in most of the Americas), you will see the wrong local time conversion.

Here's a screenshot of my chrome dev console, so you can see what I mean

截图

If I pass slashes instead:

截图

Consider using moment.js - which will accept a format parameter that will help you avoid this issue.

尝试使用以下内容:

new Date(new_d); 

The problem lies with the way you instantiate the Date . Javascript interpretes the hyphens as an utc date, and slashes as local dates.

Giving the results that mark Explains.

var utcDate = new Date('2014-01-01') // returns a UTC date
var localDate = new Date('2014/01/01'); // Returns local date

But to translate a date back to your starting point string, you can do the following.

function toDateString(utcMillis){
    var date = new Date(utcMillis);
    d = date.getDate();
    m = date.getMonth() +1;
    y = date.getFullYear();
    return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}

function addLeadingZero(n, length){
   n = n+'';
   if(n.length<length)
      return addLeadingZero('0'+n, length--);
   else
      return n;
}

If you find yourself with a UTC date, you can still do this:

function toUTCDateString(utcMillis){
    var date = new Date(utcMillis);
    d = date.getUTCDate();
    m = date.getUTCMonth() +1;
    y = date.getUTCFullYear();
    return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}

To play around with it, and see it for yourself, see this Fiddle:

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