目前以24小时时钟格式显示时间。可以更改为显示带有AM或PM的12小时时钟吗?谢谢
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
答案 0 :(得分:1)
是的,如果您想继续手动格式化,可以使用以下内容:
element.innerHTML = (h > 12 ? h - 12 : h) + ":" + m + ":" + s + (h >= 12 ? " PM" : " AM");
答案 1 :(得分:0)
new Date().toLocaleTimeString()
/* returned value: (String)
例如。上午11:25:50
或下午8:08:41 * /
答案 2 :(得分:0)
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
var ampm = h >= 12 ? 'pm' : 'am';
h = h % 12;
h = h ? h : 12;
m = m < 10 ? '0' + m : m;
var strTime = h + ':' + m + ':' + s +' ' + ampm;
document.getElementById('txt').innerHTML = strTime;
var t = setTimeout(function () { startTime() }, 500);
}
function checkTime(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
<强> DEMO 强>