Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leading zeros in minutes

Tags:

javascript

I created a clock to be placed in the header of my website. The time is not displaying a zero for minutes < 10. For example if the time is 10:50, it will only show 10:5 ,I found a solution but unsure of how to implement it. Also if there is a better method 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 the container for my clock

    <span id="clock">&nbsp</span>
like image 206
charlie Avatar asked Jan 25 '13 19:01

charlie


1 Answers

I like this way of doing things... Javascript add leading zeroes to date

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

2019 Update: But I now prefer

const d = new Date();
const date = String(d.getMinutes()).padStart(2, '0');
console.log(date); // 09;
like image 69
dmo Avatar answered Oct 08 '22 19:10

dmo