【问题标题】:toISOString() return wrong datetoISOString() 返回错误的日期
【发布时间】:2013-09-04 10:47:24
【问题描述】:

为什么这段代码返回明天的日期?

它必须返回 2013-08-31 而不是 2013-09-01,因为我们是 8 月 31 日。

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toisostring

function myFunction() {
  var d = new Date();
  var x = document.getElementById("demo");
  x.innerHTML = d.toISOString();
}
<p id="demo">Click the button to display the date and time as a string, using the ISO
  standard.</p>
<button onclick="myFunction()">Try it</button>

【问题讨论】:

标签: javascript date


【解决方案1】:

它是 UTC。

如果您想获取本地时区,您必须自己设置日期格式(使用getYear() getMonth() 等)或使用诸如date.js 之类的库来为您设置日期格式。

使用 date.js 非常简单:

(new Date()).format('yyyy-MM-dd')

编辑

正如@MattJohnson 所说,date.js 已被废弃,但您可以使用 moment.js 等替代方案。

【讨论】:

  • @Francois 使用 getYear() 等,但您在另一个问题中找到的解决方案更好。使用 date.js 更好。
  • 使用 moment.js,而不是 date.js。 It's been abandoned.
  • 使用 moment 代替 d.toISOString() 只需编写 moment(d).toISOString()。
【解决方案2】:

使用:

new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );

(function() {

    function pad(number) {
      if (number < 10) {
        return '0' + number;
      }
      return number;
    }

    Date.prototype.toISO1String = function() {
      return this.getFullYear() +
        '-' + pad(this.getMonth() + 1) +
        '-' + pad(this.getDate()) +
        'T' + pad(this.getHours()) +
        ':' + pad(this.getMinutes()) +
        ':' + pad(this.getSeconds()) +
        '.' + (this.getMilliseconds() / 1000).toFixed(3).slice(2, 5) +
        'Z';
    };

  })();

参见:mozilla.orgtoISOString 文档

我刚刚修改了它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2013-11-08
    • 2018-04-05
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多