Zidrep
Zidrep

Reputation: 57

Why does new.Date() differs 1 hour from new.Date().toISOString()?

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

Answers (2)

Rahul Tripathi
Rahul Tripathi

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

haim770
haim770

Reputation: 49095

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

(Emphasis mine)

See MDN

Upvotes: 1

Related Questions