How to get correct output of hour: “2-digit” for toLocaleString(“en-US”) with AM/PM?

自古美人都是妖i 提交于 2021-01-28 11:50:17

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/55988030/how-to-get-correct-output-of-hour-2-digit-for-tolocalestringen-us-with-am

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!