最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get correct output of hour: "2-digit" for toLocaleString("en-US") with A

programmeradmin1浏览0评论

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);

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?

Share Improve this question edited May 5, 2019 at 15:21 Peter asked May 5, 2019 at 0:58 PeterPeter 311 silver badge3 bronze badges 2
  • 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? – RobG Commented May 5, 2019 at 5:24
  • Thank you @RobG ! – Peter Commented May 5, 2019 at 15:23
Add a ment  | 

1 Answer 1

Reset to default 5

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);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论