我想显示if time is less than 10 hours or minute or seconds
然后,时间显示为"00", "01", "02","03"...
,但现在显示"0", "1", "2", "3"...
CODE:
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
document.getElementById('label').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
<body onload="startTime()">
<div id="label"></div>
</body>
检查秒数
答案 0 :(得分:2)
这有助于你:
<html>
<head>
<meta charset="utf-8">
</head>
<body onload="startTime()">
<div id="label"></div>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if (h < 10 ) { h = "0" + h;}
if (m < 10 ) {m = "0" + m;}
if (s < 10 ) {s = "0" + s;}
document.getElementById('label').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
</script>
</body>
</html>
或使用此代码:
<html>
<head>
<meta charset="utf-8">
<style>
</style>
</head>
<body onload="startTime()">
<div id="label"></div>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
h = (h < 10 ) ? ("0" + h) : h;
m = (m < 10 ) ? ("0" + m) : m;
s = (s < 10 ) ? ("0" + s) : s;
document.getElementById('label').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
</script>
</body>
</html>
答案 1 :(得分:1)
使用 queryScalar()
documentation 方法做一些棘手的事情
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
document.getElementById('label').innerHTML = ('0' + h).slice(-2) + ":" + ('0' + m).slice(-2) + ":" + ('0' + s).slice(-2);
var t = setTimeout(startTime, 500);
}
<body onload="startTime()">
<div id="label"></div>
</body>
答案 2 :(得分:1)
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//====Add this=======
if(h<10){ h = '0' + h; }
if(m<10){ m = '0' + m; }
if(s<10){ s = '0' + s; }
//===================
document.getElementById('label').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
答案 3 :(得分:0)
function pad (str) {
str = str.toString();
return str.length < 2 ? "0" + str : str;
}
只需使用此功能几小时,几分钟即可。
h = pad(h);
m = pad(m);
s = pad(s);