37

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);
Lukas
  • 7,384
  • 20
  • 72
  • 127
  • 2
    possible duplicate of [String.Format in Javascript?](http://stackoverflow.com/questions/6220693/string-format-in-javascript) – Richard Ev Sep 05 '12 at 09:27
  • The "problem" with this code is that `number.length` (e.g. `(42).length`) is *always* `undefined`. –  Sep 05 '12 at 09:35
  • 1
    the names of this topics have nothing in common with my problem... – Lukas Sep 05 '12 at 09:39

9 Answers9

58

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.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • 2
    Genious pieces of code like this are why I use S/O. Simple, to the point and why on earth didn't I ever think of this?! – Nathan Dec 05 '21 at 10:36
28

currentMinutes is a number, so it does not have the length property. Also, you must check the length before set the currentMinutes to the minutes element.

Something like:

var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();

$.ajax({
    success: function (clock) {
        if (currentMinutes.toString().length == 1) {
            currentMinutes = "0" + currentMinutes;
        }

        document.getElementById("hour").firstChild.nodeValue = currentHours;
        document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
    }
});
alex
  • 479,566
  • 201
  • 878
  • 984
Marcelo De Zen
  • 9,439
  • 3
  • 37
  • 50
15

Try using the padStart() method. Based on MDN docs, the padStart() method keeps padding the string with another string until it reaches the desired length. Link to MDN docs on padStart().

If you want to format your string to have 4 digits with leading zeros if less than 4 digits are available. The padStart() method can come to the rescue as follows:

let str = "34"

str = str.padStart(4, "0") // results in "0034"
console.log(str)

An example of the date case:

var now = new Date(); 
var year= now.getFullYear(); 
var month= (now.getMonth()+1).toString().padStart(2, "0");
var day= now.getDate().toString().padStart(2, "0");
var hour = now.getHours().toString().padStart(2, "0");
var minute = now.getMinutes().toString().padStart(2, "0");

document.getElementById("date").innerHTML =`${day}-${month}-${year}-${hour}:${minute}`;
 
<div id="date"></div>
Pouya
  • 151
  • 1
  • 6
9

currentMinutes won't have a length property, as it's a Number, not a String.

You could force it to be a String.

if ((currentMinutes+'').length == 1) {
     currentMinutes = "0" + currentMinutes;
}

But, because you have a Number, you should make your condition...

if (currentMinutes < 10) {
     currentMinutes = "0" + currentMinutes;
}

If you were especially crazy, you could do...

var hoursMinutes = ((new Date)+"").match(/\d+:\d+(?=:)/)[0].split(":");
alex
  • 479,566
  • 201
  • 878
  • 984
2

Based on the other awnsers, I created this lines of code:

var now = new Date(); 
var dd = now.getDate(); 
var mm = now.getMonth()+1;
var y = now.getFullYear(); 
var h = now.getHours();
var m = now.getMinutes();

function aZero(n) {
  return n.toString().length == 1 ?  n = '0' + n: n;
}

document.getElementById("out").innerHTML =
  aZero(dd) + "-" +
            aZero(mm) + "-" +
            y +  "   -  "   +
            aZero(h)  + ":" +
            aZero(m);
<div id="out">my time :D</div>

Cu next time.

Johan Hoeksma
  • 3,534
  • 5
  • 28
  • 40
1

You could also check sprintf() for javascript.

You could go with something as simple as:

sprintf("%02d:%02d", currentHours, currentMinutes);

Using functions that accept formatting lets you have much more control over your output, when you need to.

dureuill
  • 2,526
  • 17
  • 24
1

in android(build in)

String time=String.format("%02d:%02d",hourOfDay,minute);

in javascript use (sprintf.js)

int i = 1;
string s = sprintf("%02d", i);
document.write(s); // Prints "01"

sprintf.js: http://www.diveintojavascript.com/projects/javascript-sprintf

sms247
  • 4,404
  • 5
  • 35
  • 45
1

Try use ('0' + currentTime.getHours()).slice(-2)

Updated your Question -

window.setInterval(function update_clock() {
    var currentTime = new Date();
    var currentHours = ('0' + currentTime.getHours()).slice(-2);
    var currentMinutes = ('0' + currentTime.getMinutes()).slice(-2);
    $.ajax({
        success: function (clock) {
            document.getElementById("hour").firstChild.nodeValue = currentHours;
            document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
            if (currentMinutes.length == 1) {
                currentMinutes = "0" + currentMinutes;
            }
        }
    });
}, 999);
Dhana
  • 1,618
  • 4
  • 23
  • 39
0

You could do based on length.

My solution will be

  var mnt = '' + (seconds / 60).toFixed();
  if (mnt.toString().length == 1) mnt = '0' + mnt;
  var sec = '' + (seconds % 60).toFixed();
  if (sec.toString().length == 1) sec = '0' + sec;
  return `${mnt}:${sec}`;
Mithun Billara
  • 140
  • 1
  • 6
Sumit
  • 1,022
  • 13
  • 19