2

According to the toLocaleString() MDN Documentation the option hour: "2-digit" should return a 2 digit representation of the hour, but it returns only 1 digit if the locale is en-US and the format is AM/PM. (Update: AM/PM mention)

let d = new Date("2019-05-03 15:00:00").toLocaleString("en-US", {hour: "2-digit", minute: "2-digit"});
console.log(d);

Is there a workaround or another easy way to get the 2-digit hour for the US locale, displaying the AM and PM?

Peter
  • 31
  • 1
  • 3
  • *Date.prototype.toLocaleString* is somewhat quirky. A library will often give better results, or at least you can chose one that behaves as you require. :-) BTW, in Safari your code snippet returns *Invalid Date*, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG May 05 '19 at 05:24
  • Thank you @RobG ! – Peter May 05 '19 at 15:23

1 Answers1

3

You just have to explicitly disable the 12 hour representation in the options :

    let d = new Date("2019-05-03 15:00:00").toLocaleString("en-US", {hour: "2-digit", minute: "2-digit", hour12: false});
    console.log(d);

The 2 digits parameter might be related to padding, but I don't think it's absolutely necessary. I would consider removing it.

    let d = new Date("2019-05-03 15:00:00").toLocaleString("en-US", {hour12: false});
    console.log(d);
John Krakov
  • 355
  • 1
  • 8
  • Thanks! That fixes the 2 digits, but I need also the AM/PM format (maybe didn't explained that well enough - added more info about it in the question) – Peter May 05 '19 at 15:19
  • AM/PM and 24H are too opposed time format since the 24H time cycle removes the ambiguity between for example 3h PM and 3h AM. If you really want to do it though, you should just edit the string : d = Number(d.split(":")[0]) => 12 ? d + " PM" : d + " AM" – John Krakov May 05 '19 at 15:26