Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

javascript - toISOString() return wrong date

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...