我现在研究了一小时如何在小时,分钟或秒小于10时添加零,以制作它们,例如“05小时”,而不仅仅是“5小时”。
我已经尝试了if (hours < 10) { hours = "0" + hours }
,我发现它可以在几个网站中使用,但它似乎不适用于我的代码。
我该如何做到这一点?
function clock() {
//Clock variables
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
var date1 = [hours, minutes, seconds];
var actualDate = date1.join(":");
//Adding zeros, but it doesn't work.
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
//text
document.getElementById("hey").innerHTML = actualDate;
//Repeat every 1000ms (1 second)
setTimeout(clock, 1000);
};
clock();
<h1 id="hey"></h1>
答案 0 :(得分:4)
这是因为您需要在对值前加零后计算date1
和actualdate
。
function clock() {
//Clock variables
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
//Adding zeros, but it doesn't work.
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var date1 = [hours, minutes, seconds];
var actualDate = date1.join(":");
//text
document.getElementById("hey").innerHTML = actualDate;
//Repeat every 1000ms (1 second)
setTimeout(clock, 1000);
};
clock();
&#13;
<h1 id="hey"></h1>
&#13;
我建议您使用ES8的 padStart
来完成此任务。
var x = "5";
console.log(x.padStart(2, "0"));
&#13;
答案 1 :(得分:0)
更好地使用此pad
函数:
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
节点中的:
> function pad(num, size) {
... var s = num+"";
... while (s.length < size) s = "0" + s;
... return s;
... }
> pad(1, 2)
'01'
> pad(11, 2)
'11'
>
答案 2 :(得分:0)
number
这只会将number
0添加到function clock() {
//Clock variables
var today = new Date();
var hours = today.getHours().toString();
var minutes = today.getMinutes().toString();
var seconds = today.getSeconds().toString();
//Adding zeros, but it doesn't work.
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var date1 = [hours, minutes, seconds];
var actualDate = date1.join(":");
//text
document.getElementById("hey").innerHTML = actualDate;
//Repeat every 1000ms (1 second)
setTimeout(clock, 1000);
};
clock();
秒。所以你必须把你的数字变成一个字符串:
<h1 id="hey"></h1>
{{1}}