我想制作一个显示当前时间的网页。单击“12 小时格式”按钮时,div 区域将显示 12 小时制的时间。单击“24 小时格式”按钮时,时间将在 div 区域显示为 24 小时制。当前单击这些按钮时没有任何反应。帮助!
HTML:
<html>
<head>
<title>Clock</title>
<script type="text/javascript" src="clock.js"></script>
</head>
<body>
<div id="textbox"></div>
<br/>
<button type="radio" onclick="getTwelveHrs()">12 Hour Format</button>
<button type="radio" onclick="getTwentyFourHrs()">24 Hour Format</button>
</body>
</html>
JavaScript:
function getTwelveHours{
if (i < 10) {
i = "0" + i;
}
return i;
}
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('textbox').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
function getTwentyFourHrs() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('textbox').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(function() {
startTime()
}, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
最佳答案
为什么不使用像 Moment.js 这样的库来为你做这件事。
H, HH 24 hour time
h, or hh 12 hour time (use in conjunction with a or A)
所以在使用 moment.js 时只需在 JavaScript 中使用这段代码
moment() 方法以您的特定格式返回当前日期。因此,当您的用户单击按钮时,您可以在每个按钮上调用以下方法
moment().format("YYYY-MM-DD HH:mm"); // 24H clock
moment().format("YYYY-MM-DD hh:mm"); // 12H clock
没有测试过,但应该可以用
关于javascript - 显示 12 小时制和 24 小时制时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26043820/