我正在使用实时html和javascript时钟。这段代码几乎是完整的,但是我不希望时钟显示军事时间,
这是我尝试过的方法:
<!DOCTYPE html>
<html>
<head>
<script>
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('time').innerHTML =
h + ":" + m + ":" + s + `<strong>a.m.</strong>`;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function unMilitary() {
if (h = 13) {h = 1}
if (h = 14) {h = 2}
if (h = 15) {h = 3}
if (h = 16) {h = 4}
if (h = 17) {h = 5}
if (h = 18) {h = 6}
if (h = 19) {h = 7}
if (h = 20) {h = 8}
if (h = 21) {h = 9}
if (h = 22) {h = 10}
if (h = 23) {h = 11}
if (h = 24) {h = 12}
return h;
}
</script>
</head>
<body onload="startTime()">
<div id="time"></div>
<p>
(for those of you who are viewing this time in midday, it is displaying military time.)
</p>
</body>
</html>
unMilitary
函数不起作用,有什么建议吗?
这是jsfiddle中的代码。
答案 0 :(得分:0)
if (h = 13) {h = 1}
您在条件=
中使用h = 13
运算符,因此if
语句的条件将13分配给h
。这不是您想要的;使用h == 13
。
但是,更简单的解决方案是:
if (h > 12) {
return h - 12;
} else if (h == 0) { // you probably forgot about this case
return 12;
} else {
return h;
}
答案 1 :(得分:0)
使用本机javascript和toLocaleString
函数,然后拆分结果,是解决此问题的简便方法。另外,您可以使用setInterval
代替必须多次调用的setTimeout
function getTimeCurrentTime() {
let time = new Date();
// toLocaleString in us format outputs 8/2/2019, 10:14:54 PM
// we can then split that by comma and space and take last part of it
return time.toLocaleString('en-US').split(', ')[1];
}
function updateCurrentTime() {
let timeNode = document.getElementById('time');
timeNode.innerHTML = getTimeCurrentTime();
}
setInterval(updateCurrentTime, 1000);
<div id="time"></div>
答案 2 :(得分:0)
为避免军事时间,请在if语句中表示小时是否大于12时,从小时中减去12
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if(h >12) {
h = h - 12;
document.getElementById('ampm').innerHTML = "P.M";
}
document.getElementById('ampm').innerHTML = "A.M";
document.getElementById('time').innerHTML =
h + ":" + m + ":" + s ;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="time" style="display: inline-block;"></div> <a id='ampm'></a>
<p>
(for those of you who are viewing this time in midday, it is displaying
military
time.)
</p>
</body>
</html>