Sometimes you’d want to fill in digits with zeroes instead of nothing when showing time or something similar. For instance, you’d probably want to show 12:05 instead of 12:5 for a time of 12 hours and 5 minutes. The problem with this is that in the actual data, you’ll have hours data as 12 and minutes data as 5. In such cases, you’d want to add an extra zero to the 5. You can take advantage of the padStart() function provided by JavaScript and make a helper function to attain the functionality. Here I’m showing a few samples to demonstrate the same:
function getZeroPadding(num, places) {
return String(num).padStart(places, '0')
}
function formatTime(hours, mins) {
return `${getZeroPadding(hours, 2)}:${getZeroPadding(mins, 2)}`
}
const someTime = {
Hh: 12,
mm: 5,
}
const anotherTime = {
Hh: 3,
mm: 10,
}
const someAnotherTime = {
Hh: 7,
mm: 7,
}
console.log(formatTime(someTime.Hh, someTime.mm))
console.log(formatTime(anotherTime.Hh, anotherTime.mm))
console.log(formatTime(someAnotherTime.Hh, someAnotherTime.mm))
//output
12:05
03:10
07:07
Code language: JavaScript (javascript)
In the above code, I’ve created a function called getZeroPadding which takes in two arguments. The first one accepts the actual number and the second one adds the number of paddings. For example, getZeroPadding(5,2) would produce “05” while getZeroPadding(5,3) would produce “005”. The formatTime function above would format the result of getZeroPadding with a colon in between.