Reputation: 93
Good day,
I've been using the following time function JS in an HTML code. I'm still in the progress of learning and understanding JS and been playing around with it. However, I recently noticed that whenever my minutes are less than 10, the 0 is taken away, say 14:5 instead of 14:05. Is there quick format way to fix this?
Thanks in advance, here's the JS function
function updateClock() {
var now = new Date(),
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
time = now.getHours() + ':' + now.getMinutes();
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
// set the content of the element with the ID time to the formatted string
// document.getElementById('time').innerHTML = [date, time].join(' ');
document.getElementById('time').innerHTML = ["Today is", date, "and the time is", time].join(' ');
setTimeout(updateClock, 1000);
}
updateClock();
Upvotes: 1
Views: 257
Reputation: 5055
Just use one more format function like this and call it everywhere:
function zero(num) {
return num < 10 ? '0' + num : num;
}
Upvotes: 0
Reputation: 76597
You should be able to check if your minutes value is less than 10 and append a 0
to the front of it :
// If the minutes are greater than 10, pad them with a '0'
time = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
Example
You can see a working example here and demonstrated below :
Upvotes: 1
Reputation: 1888
As far as I know, there is no built-in method for this. However, you can use a ternary operator to add the 0 when necessary.
var mins = now.getMinutes();
var minsFixed = mins < 10 ? '0' : '' + mins;
time = now.getHours() + ':' + minsFixed;
Upvotes: 0