Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 282
Francois Avatar asked Sep 01 '13 01:09

Francois


People also ask

What is toISOString()?

The toISOString() method returns a date object as a string, using the ISO standard. The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ.

Does toISOString convert to UTC?

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .

How to convert date to iso string in JavaScript?

toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ).


1 Answers

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.

like image 68
soulcheck Avatar answered Sep 29 '22 19:09

soulcheck