这是最终结果。我正在对其进行更新,以便将来可以将类似我最初发布的问题(如何制作12小时制)转发给该线程以供参考。感谢MrChief的帮助!
<html>
<head>
<script type="text/javascript">
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length) {
str = padString + str;
}
return str;
}
function timeNow() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var tt = (h >= 12) ? " pm" : " am";
time = (h - 12).toString().lpad("0", 2) + ":" + m.toString().lpad("0", 2) + ":" + s.toString().lpad("0", 2) + tt;
document.getElementById('txt').innerHTML=time;
var timer = setTimeout(timeNow,500);
}
</script></head>
<body onload="timeNow()">
<div id="txt"></div>
</body></html>
最佳答案
也许你是说
i="0" + i + "am";
^
并且您的
checkTime
函数缺少关闭括号。更新:
有更好的填充方法。这是一个修改
string
的prototype的函数,该函数向字符串对象添加了一个左填充函数。//pad left
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
}
使用它,您的函数将变得更加简单:
function timeNow() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var tt = (h >= 12) ? " pm" : " am";
time = h.toString().lpad("0", 2) + ":" + m + ":" + s.toString().lpad("0", 2) + tt;
alert(time);
}
演示:http://jsfiddle.net/mrchief/kTQnM/7/
这是使用您的HTML的完整演示:http://jsfiddle.net/mrchief/kTQnM/10/