早上好,有没有人知道如何修改这个倒计时代码,以便它总是输出两位数,即01 01 01,而不是1 1 1
<script>
$(document).ready(function () {
setInterval(function () {
var now = new Date();
var day = now.getDay();
var end;
if(day >= 1 && day <= 5) {
end = new Date(now.getYear(), now.getMonth(), day, 14, 0, 0, 0);
} else {
end = new Date(now.getYear(), now.getMonth(), day, 13, 0, 0, 0);
}
var timeleft = end.getTime() - now.getTime();
ar diff = new Date(timeleft);
$("#countdownTimer").html(diff.getHours() + " " + diff.getMinutes() + " " + diff.getSeconds());
}, 1000);
});
</script>
谢谢你们
答案 0 :(得分:1)
您可以使用日期库或简单的填充函数,如下所示:
function padNumber(num, size){
var s = "0000000000" + num;
return s.substr(s.length - size);
}
所以对于你的代码:
$("#countdownTimer").html(padNumber(diff.getHours(), 2) + " "
+ padNumber(diff.getMinutes(), 2) + " "
+ padNumber(diff.getSeconds(), 2));
注意: 这个简单的函数不会检查num本身的长度,因此指定太小的大小会截断它(但你明白了)。 < / p>
虽然不是防弹,但这比此处提供的链接上的3个最佳选项更快:How can I pad a value with leading zeros?
jsPerf: http://jsperf.com/left-zero-pad/14
或者如果您想要更简单,更快(但仅限2位数)
function pad2(num){
if(num < 10){
return "0" + num;
}
return "" + num;
}
注意:最后一个版本是 soooo ,它会让其他选项死掉(比之快20倍)。
答案 1 :(得分:0)
这个简单的功能应该可以解决问题。
function makeTwoDigit(num)
{
num = num.toString();
if(num.length==1)
return "0"+num;
return num;
};
setInterval(function () {
var now = new Date();
var day = now.getDay();
var end;
if(day >= 1 && day <= 5) {
end = new Date(now.getYear(), now.getMonth(), day, 14, 0, 0, 0);
} else {
end = new Date(now.getYear(), now.getMonth(), day, 13, 0, 0, 0);
}
var timeleft = end.getTime() - now.getTime();
var diff = new Date(timeleft);
console.log(makeTwoDigit(diff.getHours()) + " " + makeTwoDigit(diff.getMinutes()) + " " + makeTwoDigit(diff.getSeconds()));
}, 1000);