+ 1
Easier way to manipulate the html paragraph
So I have a timer variable, and this variable points to a paragraph in html. The code is time.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.
2 Respuestas
+ 3
Otherwise you could use a utility function.
function leftPad(time) { return time <10 ? "0" + time : time}
And then e.g timer.innerHTML = [hr,min,sec].map(leftPad).join(":")
+ 3
You can eg. use Intl.DateTimeFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat