将Date()转换为IsoString并没有显示正确的hh:mm:ss

时间:2017-05-02 08:39:09

标签: javascript date data-conversion isodate

我有一个像这个const date = new Date()的日期变量,当我在console.log时,它显示了我2017年5月2日星期二11:35:50 GMT + 0300(GTB日光时间)这当然是正确的。我想将其转换为Iso Date,并使用javascript的toIsoString()函数,如下所示:

const IsoDate = (date.toISOString()).slice(0, -5);
      console.log(IsoDate)

但它在控制台中显示了我: 2017-05-02T08:35:50它似乎在实际日期前3小时显示。为什么会这样?

3 个答案:

答案 0 :(得分:3)

因为它在GMT [格林威治时区]给出了时间。 toISOString 方法始终为UTC。

要获取ISO字符串保留时区,请使用此功能

    function formatLocalDate() {
//pass date whatever u want
        var now = new Date(),
            tzo = -now.getTimezoneOffset(),
            dif = tzo >= 0 ? '+' : '-',
            pad = function(num) {
                var norm = Math.abs(Math.floor(num));
                return (norm < 10 ? '0' : '') + norm;
            };
        return now.getFullYear() 
            + '-' + pad(now.getMonth()+1)
            + '-' + pad(now.getDate())
            + 'T' + pad(now.getHours())
            + ':' + pad(now.getMinutes()) 
            + ':' + pad(now.getSeconds()) 
            + dif + pad(tzo / 60) 
            + ':' + pad(tzo % 60);
    }

Ofcourse Best Option是Moment JS:)

答案 1 :(得分:2)

如果您想使用 toISOString 但是在您的时区中获取当前日期,您可以先按偏移调整UTC分钟,然后添加时区字符串,例如

&#13;
&#13;
function toISOStringLocal(date) {
  // Copy date so don't modify original
  var d = new Date(+date);
  var offset = d.getTimezoneOffset();
  var sign = offset < 0? '+' : '-';
  // Subtract offset as ECMAScript offsets are opposite to usual
  d.setUTCMinutes(d.getUTCMinutes() - d.getTimezoneOffset());
  // Convert offset to string
  offset = ('0' + (offset/60 | 0)).slice(-2) + ('0' + (offset%60)).slice(-2);
  return d.toISOString().replace(/Z\s*/i,'') + sign + offset;
}

console.log('Current date: ' + toISOStringLocal(new Date()));
&#13;
&#13;
&#13;

您还可以向Date原型添加方法:

&#13;
&#13;
// Return local date in ISO 8601 format
if (!Date.prototype.toISOStringLocal) {
  Date.prototype.toISOStringLocal = function() {
    var d = new Date(+this);
    var offset = d.getTimezoneOffset();
    var sign = offset < 0? '+' : '-';
    d.setUTCMinutes(d.getUTCMinutes() - d.getTimezoneOffset());
    offset = ('0' + (offset/60 | 0)).slice(-2) + ('0' + (offset%60)).slice(-2);
    return d.toISOString().replace(/Z\s*/i,'') + sign + offset;
  };
}

// Return UTC date in ISO 8601 format
if (!Date.prototype.toISODate) {
  Date.prototype.toISODate = function() {
    return d.toISOString().substr(0,10);
  };
}

var d = new Date();

console.log('The current local date is: ' + d.toISOStringLocal() + 
          '\nThe current UTC date is  : ' + d.toISODate()
);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

引用到ISOString documentation

  

......时区始终为零UTC偏移......

时区始终设置为UTC 0.这就是为什么我和你的价值相同而且我在不同的时区。