Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

javascript - Adding "0" if clock have one digit

i have some clock script. Everything is fine and it's work perfectly but... i have one problem. If at the clock is set one digit hour or minute like 1:5 clock not adding "0" digit before. This what i'v done but it does't work. Can u help me, much thx?

window.setInterval(function update_clock() {
    var currentTime = new Date();
    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    $.ajax({
        success: function (clock) {
            document.getElementById("hour").firstChild.nodeValue = currentHours;
            document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
            if (currentMinutes.length == 1) {
                currentMinutes = "0" + currentMinutes;
            }
        }
    });
}, 999);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may use .slice to extract a portion of a string. Pass a negative number to it, in order to slice from the end of the string.

Therefore, the following is possible, and quite simple:

('0'+currentMinutes).slice(-2)

Concatenating with '0' makes sure that the target of the operation will always be a string. ('0'+currentMinutes) will yield a 2 or 3 letter string ("07" or "017", for instance). Slicing the last two characters off that string will give you a 0-padded two-digit number.

Note that the above would yield "00" if currentMinutes is 100, so it assumes that you know the values you'll be working with.

This could be extracted to something more reusable:

Number.prototype.zeroPad = function() {
   return ('0'+this).slice(-2);
};

That would allow you to write:

currentMinutes.zeroPad();

You could also make the length of the padding variable:

Number.prototype.zeroPad = function(length) {
   length = length || 2; // defaults to 2 if no parameter is passed
   return (new Array(length).join('0')+this).slice(length*-1);
};

Which could be called as:

currentMinutes.zeroPad(); // e.g. "07" or "17"
currentMinutes.zeroPad(3); // e.g. "007" or "017"

Note that while currentMinutes.zeroPad() will work, 7.zeroPad() would not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...