倒数两位数

时间:2012-11-21 18:08:19

标签: javascript countdown

我有这个脚本并且工作得很好,但是我想将它更改为两位数,我的意思是,如果剩下2天则将其显示为02天。这是脚本:

    <script>
function renderMessage(dateStr, msg1, msg2, countFrom) {
  var date = new Date(dateStr);
  var now = new Date();
  var diff = date.getTime() - now.getTime();
  var days = Math.floor(diff / (1000 * 60 * 60 * 24)) + 1;
  if(days < 1) {
    document.write(msg1);
  } else {
    if(countFrom)
      days = countFrom - days;
    document.write(msg2.replace(/%days%/g, number_format(days)));
  }
}
function number_format(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num)) {
    num = "0";
  }
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  num = Math.floor(num/100).toString();
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
  num = num.substring(0,num.length-(4*i+3))+','+
  num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + num);
}
</script>


<script>
  renderMessage("November 29, 2012", "You missed it!", "Hurry, there's only %days% days to go!");
</script>

我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

为任何小于10的数字添加条件:

  if (num < 10)
    num = "0" + Math.floor(num/100).toString();
  else
    num = Math.floor(num/100).toString();