toISOString()返回错误的日期 [英] toISOString() return wrong date

查看:149
本文介绍了toISOString()返回错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

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>点击按钮,使用ISO标准将日期和时间显示为字符串。< / p>< button onclick =myFunction()>尝试它< / button>  

解决方案



如果您想获得当地时区,您必须自己格式化日期(使用 getYear() getMonth()等),或者使用像 date.js 将格式化您的日期。



使用date.js很简单:

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

编辑



由于@MattJohnson注意到date.js已被放弃,但您可以使用 moment.js


Why did this piece of code return tomorrow's date ?

It must return 2013-08-31 and not 2013-09-01 as we are August 31st.

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>

解决方案

It's in UTC.

If you want to get your local timezone you have to format the date yourself (using getYear() getMonth() etc.) or use some library like date.js that will format the date for you.

With date.js it's pretty simple:

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

edit

As @MattJohnson noted date.js has been abandoned, but you can use alternatives like moment.js.

这篇关于toISOString()返回错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆