Reputation: 295
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>
Upvotes: 13
Views: 24958
Reputation: 162
You can simply use Luxon.
DateTime.fromJSDate(new Date(yourDateVariable)).toFormat('yyyy-MM-dd')
Upvotes: 0
Reputation: 1357
use:
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );
or
(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';
};
})();
See: mozilla.org toISOString doc
I just modified it
Upvotes: 6
Reputation: 36767
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.
Upvotes: 6