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 tried this way. It's not brief 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
Since you're likely to run into presentational issues in the future along the same lines, I'd recommend picking a favorite string formatting function for Javascript.
Some examples:
Then you can do something like "{0:00}:{1:00}".format(current.getHours(), current.getMinutes())
or even better,
var d = new Date();
var s = d.format("hh:mm:ss tt");
// Result: "02:28:06 PM"
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;
You can just grab the first 5 characters of the time string.
(new Date()).toTimeString().substr(0,5)
And what is your issue?
var minutes = (current.getMinutes() < 10? '0' : '') + current.getMinutes();
Since you'll have the same problem with hours, 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())