admin管理员组

文章数量:1314442

I would like to display this as something like: 4:26 PM.

But what I keep getting is: 04:26 PM.

If I remove the hour and minute options from toLocaleTimeString(), it works, but it also displays seconds, which I don't want.

myClock();
function myClock() { 
    var d = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});   
    document.getElementById("clock").innerHTML = d; 
}
setInterval(myClock, 1000);
<div id="clock"></div>

I would like to display this as something like: 4:26 PM.

But what I keep getting is: 04:26 PM.

If I remove the hour and minute options from toLocaleTimeString(), it works, but it also displays seconds, which I don't want.

myClock();
function myClock() { 
    var d = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});   
    document.getElementById("clock").innerHTML = d; 
}
setInterval(myClock, 1000);
<div id="clock"></div>

Share Improve this question edited Feb 18, 2021 at 21:49 scott.schaffer asked Feb 18, 2021 at 21:37 scott.schafferscott.schaffer 6538 silver badges22 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

You're setting the 2-digit format for hours; sounds like you want numeric instead:

myClock();
function myClock() { 
    var d = new Date().toLocaleTimeString([], {hour: 'numeric', minute:'2-digit'});   
    document.getElementById("clock").innerHTML = d; 
}
setInterval(myClock, 1000);
<div id="clock"></div>

(Note that this may depend on the specific locale; the above is true for en-US. The rules for determining the locale when not explicitly specified are in part based on individual user settings; if you need everyone to see the exact same formatting, you may want to substitute en-US in place of the first argument to toLocaleTimeString. (Though of course that defeats the purpose of having locales in the first place!)

本文标签: javascripttoLocaleTimeString() always showing leading zeroStack Overflow