Why do I get hours wrong from date in Javascript?

Viewed 1061

I want to get the hours and minutes from a date string so I convert it to a date and then use the getHours() and getMinutes() methods. Problem is that the result is 12:20 instead of 10:20. Why does this happen and how can I get the right hour?

function myFunction() {
  var d = new Date("2020-05-28T10:20:00.000Z");
  hours = d.getHours();
  minutes = d.getMinutes();
  document.getElementById("demo").innerHTML = hours + ":" + minutes;
}

myFunction();
<div id="demo"></div>

Here you have a JSFiddle to try it:

https://jsfiddle.net/oqLsna0e/1/

Thank you!

2 Answers

The getHours method is retrieving the hours according to where the app is hosted. In your case the app must be hosted in a CEST timezone (GMT+2).

You need to use the getUTCHours method to get the hours in UTC since that is how you are specifying the date using ZULU.

The z at the end of the string means zero hour offset that is UTC. Date.getHours returns the hour according to your local time so it is not wrong. Date.getUTCHours returns the UTC+-0 hour.

If you need to work with timezones there are plenty of libraries such as day.js or date-fns.

Related