Leading zeros in minutes

I created a watch that will be placed in the title of my site. Time does not display zero for minutes <10. For example, if the time is 10:50, it will only show 10: 5, I found a solution, but I don’t know how to implement it. Also, if there is a better way, please share.

 var current;
window.onload = function () {

    current = new Date();

    document.getElementById("clock").innerHTML = current.getHours() + ":" +      current.getMinutes(); 

This is what I need

                if (minutes < 10)
                minutes = "0" + minutes

and this is a container for my watch

    <span id="clock">&nbsp</span>
+6
source share
5 answers

Since you are likely to encounter presentation problems in the future in the same vein, I would recommend choosing the favorite string formatting function for Javascript.

Some examples:

- "{0:00}:{1:00}".format(current.getHours(), current.getMinutes()) ,

var d = new Date();
var s = d.format("hh:mm:ss tt");
// Result: "02:28:06 PM"
+9

5 .

(new Date()).toTimeString().substr(0,5)
+24

And what is your problem?

var minutes = (current.getMinutes() < 10? '0' : '') + current.getMinutes();

Since you will have the same problem with the clock, wrap it in a small utility function:

function pad(var value) {
    if(value < 10) {
        return '0' + value;
    } else {
        return value;
    }
}

And later, simply:

pad(current.getHours()) + ":" + pad(current.getMinutes())
+12
source

I like this way of doing things ... Javascript adds leading zeros to the date

const d = new Date();
const date = ('0${d.getMinutes()}').slice(-2);
console.log(date); // 09;

2019 Update: But Now I Prefer

const d = new Date();
const date = String(d.getMinutes()).padStart(2, '0');
console.log(date); // 09;
+4
source

I tried this way. This is not short, but it works.

var dt = new Date();
if (parseInt(dt.getMinutes()) < 10) {minutes = "0" + dt.getMinutes();} else minutes = dt.getMinutes();
if (parseInt(dt.getSeconds()) < 10) {seconds = "0" + dt.getSeconds();} else seconds = dt.getSeconds();

var time = dt.getHours() + ":" + minutes + ":" + seconds;
document.write("Now is:" + time);

//Result: Now is: 22:47:00

I hope it will be useful

+1
source

All Articles