2

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!

segFault
  • 3,887
  • 1
  • 19
  • 31
User1
  • 127
  • 1
  • 14
  • Use: new Date('2020-05-28 10:20:00'), remove .000Z – Aks Jacoves Jun 14 '20 at 18:39
  • 1
    @AksJacoves Do not do that. It relies on a non-specified date/time format and breaks in some browsers. – str Jun 14 '20 at 18:41
  • @str I did not know that. Thanks for the info – Aks Jacoves Jun 14 '20 at 18:43
  • @AksJacoves You're welcome :) Maybe you would like to read [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript) to learn more. – str Jun 14 '20 at 18:45

2 Answers2

3

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.

Matthew Formosa
  • 468
  • 3
  • 9
3

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.

Isidrok
  • 2,015
  • 10
  • 15