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
1 Answer
Reset to default 12You'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
版权声明:本文标题:javascript - toLocaleTimeString() always showing leading zero - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741970960a2407835.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论