Reputation: 57
Please someone explain me this situation.
I have the following code:
<p>Click the button to display the date and time as a string, using the ISO standard.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo1"></p>
<p id="demo"></p>
<script>
function myFunction() {
var d = new Date();
var n = d.toISOString();
document.getElementById("demo1").innerHTML = d;
document.getElementById("demo").innerHTML = n;
}
</script>
And I get the following result:
Click the button to display the date and time as a string, using the ISO standard.
Try it
Mon Apr 06 2015 19:07:55 GMT+0100 (GMT Daylight Time)
2015-04-06T18:07:55.739Z
Why does the toISOString()
method "take" 1 hour away from new Date()
???
Upvotes: 4
Views: 6797
Reputation: 172418
The trailing Z(because of which you are facing the difference) which represents Zulu timezone. Your actual time is perhaps 1 hour ahead of the GMT time. And if you want to get rid of the difference because of that you can try this:
var x = (new Date()).getTimezoneOffset() * 60000;
var localISOTime = (new Date(Date.now() - x)).toISOString().slice(0,-1);
On a side note:
moment.js
is good option to choose to get rid of these issues.
Upvotes: 6