使用javascript将UTC转换为标准日期时间格式

时间:2014-06-24 20:37:39

标签: javascript date utc

如何使用Javascript将UTC时间转换为正确的日期 - 时间格式?

这就是我想做的事情

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? 
}

现在如何,我可以获得orignal日期 - 2014-01-01来自1388534400000?

****另外,请注意,当我这样做时---新日期(1388534400000);它给的日期少了1天。 也就是说,它不是给 2014年1月1日,而是给出 2013年12月31日。但是,我想要2014年1月1日。****

有没有办法与toUTC()方法相反?

// _________对于那些toUTC()不起作用的人

" toUTC"方法适用于我的chrome控制台 见下面的屏幕截图

enter image description here

3 个答案:

答案 0 :(得分:2)

当您将包含连字符的字符串传递给Date构造函数时,它会将其视为UTC。如果你不打发时间,它会认为是午夜。如果您所在的时区落后于UTC(例如在大多数美洲地区),您将看到错误的本地时间转换。

这是我的chrome dev控制台的屏幕截图,所以你可以看到我的意思

screenshot

如果我改为使用斜杠:

screenshot

考虑使用moment.js - 它将接受一个格式参数,以帮助您避免此问题。

答案 1 :(得分:1)

尝试使用以下内容:

new Date(new_d); 

答案 2 :(得分:1)

问题在于实例化日期的方式。 Javascript将连字符解释为utc日期,并将斜杠解释为本地日期。

给出标记解释的结果。

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

但是要将日期转换回起点字符串,您可以执行以下操作。

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;
}

如果您发现自己的UTC日期,您仍然可以这样做:

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:

相关问题