Copy link to clipboard
Copied
The function below prints the time using the 24hr clock format. When the hours, minutes and seconds are less than 10, the time value is printed in a single digit format. Can someone give me an idea of how to format the time so that it always prints in a double digit format.
For instance the time 21:0:5 would be 21:00:05
alert(runTime())
function runTime () {
try{
var digital = new Date();
var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();
var milliseconds = digital.getMilliseconds();
militaryTime = hours + ":" + minutes + ":" + seconds;
return militaryTime;
} catch(e) {alert(e)}
}
Copy link to clipboard
Copied
var theNumber = 5;
alert (bufferNumberWithZeros(theNumber, 2));
////// buffer number with zeros //////
function bufferNumberWithZeros (number, places) {
var theNumberString = String(number);
for (var o = 0; o < (places - String(number).length); o++) {
theNumberString = String("0" + theNumberString)
};
return theNumberString
};
Copy link to clipboard
Copied
Thank you!
Copy link to clipboard
Copied
alert(time());
function time(){
var date = new Date();
var d = date.getDate();
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
if (hours <= 9) hours = "0" + hours;
if (minutes <= 9) minutes = "0" + minutes;
if (seconds <= 9) seconds = "0" + seconds;
todaysDate = hours + ":" + minutes + ":" + seconds;
return todaysDate.toString();
};
Copy link to clipboard
Copied
Thank you!
Copy link to clipboard
Copied
While both of the above answers are correct, I prefer the following method as it is slightly more succinct:
function makeTwoCharString(intIn){
return ("0" + intIn.toString()).slice(-2);
}
As long as the input is between 0 and 99 (inclusive) it will return the desired two digit string.
Combining with your code gives:
alert(runTime());
function runTime () {
try{
var digital = new Date();
var hours = makeTwoCharString(digital.getHours());
var minutes = makeTwoCharString(digital.getMinutes());
var seconds = makeTwoCharString(digital.getSeconds());
militaryTime = hours + ":" + minutes + ":" + seconds;
return militaryTime;
} catch(e) {alert(e)}
}