So I have a timer
variable that points to a paragraph in html.
Now I want to change the contents of this paragraph to display time
timer.innerHTML = hr ":" min;
Note: hr and min are variables that store the current time.
So, in order to avoid a situation where the time shows as "9:7" when it's 09:07am, I added a bunch of if statements
If(hr < 10){
timer.innerHTML = "0" hr ":" min;
}
If (min < 10){
timer.innerHTML = hr ":" min;
}
However, I want to do so for hours, minutes, and seconds aswell. Is there a more efficient way to do this rather than with a bunch of if statements. Because it might become quite tedious to write if statements for every possiblity.
CodePudding user response:
Try this, with a ternary conditional operator (see the docs on MDN for help):
time.innerHTML = (hr < 10 ? '0' : '') hr ':' (min < 10 ? '0' : '') min;
Here's the MDN documentation for the conditional operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
CodePudding user response:
Use String.prototype.padStart()
to pad a string with another string, in this case '0'
until it reaches the desired length, which is 2 in this case. (1)
function printTime(hour, minute) {
const hr = hour.padStart(2, 0)
const min = minute.padStart(2,0)
console.log('The time is ' hr ':' min)
}
printTime('12', '45')
printTime('1', '4')
printTime('5', '12')
Since it's a string prototype function, the input either needs to be a string or converted into one. So if you want to use numbers there are a couple of ways you can do it:
function printTime(hour, minute, second) {
const hr = ('' hour).padStart(2, 0) // Convert to string in an expression
const minString = minute '' // Convert and store in a variable
const min = minString.padStart(2,0)
const sec = second.toString().padStart(2,0) // Use toString()
console.log(`The time is ${hr}:${min}:${sec}`)
}
printTime(12, 45, 2)
printTime(1, 2, 5)
printTime(5, 20 ,59)
I know you didn't ask, but if you look at the console log above, I used template literals to make the final string. They let you interpolate strings with variables and expressions in a cleaner, easier to write, and sexier way. (2)
CodePudding user response:
a fun way to do it, using intl api :
const myDateFormat = new Intl.DateTimeFormat( undefined, {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12:false
}) ;
const hr = 8, min = 9, sec = 7 ;
console.log( myDateFormat.format( new Date(0,0,0, hr, min, sec ) ) ) ;
08:09:07
edit > some links around intl :
https://devhints.io/wip/intl-datetime
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
https://hacks.mozilla.org/2014/12/introducing-the-javascript-internationalization-api/