在数字时钟中添加零

时间:2018-03-04 19:17:26

标签: javascript

我现在研究了一小时如何在小时,分钟或秒小于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>

3 个答案:

答案 0 :(得分:4)

这是因为您需要在对值前加零后计算date1actualdate

&#13;
&#13;
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;
&#13;
&#13;

我建议您使用ES8的 padStart 来完成此任务。

&#13;
&#13;
var x = "5";
console.log(x.padStart(2, "0"));
&#13;
&#13;
&#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}}