Sat Oct 23 2021·2 min read
Photo by William Recinos
To change the
getSeconds() method to 2 digits:
getSeconds()to a string.
padStart()method to add a leading zero if it's necessary.
padStartmethod allows us to add a leading zero to the start of the string until it reaches a specified target length.
const date = new Date('March 14, 2025 05:24:07'); const seconds = String(date.getSeconds()).padStart(2, '0'); console.log(seconds); // 👉️ 07
The padStart method has to be used on a string, so the first step is to convert the number of seconds to a string.
We passed the following 2 parameters to the
padStartmethod should return, once it has been padded.
We know that the seconds should always have a length of
2, so that's what we
set as a target length.
padStartmethod would not add an additional leading zero, because we've set the
const date = new Date('March 14, 2025 13:24:22'); const seconds = String(date.getSeconds()).padStart(2, '0'); console.log(seconds); // 👉️ 22
The seconds were set to
22 (2 digits), so the
padStart method didn't add a
padStartmethod is not supported in Internet Explorer. If you have to support the browser, use the next approach covered in this article.
To change the
getSeconds() method to 2 digits, check if the seconds are less
than or equal to
9, if they are, add a leading zero to the seconds using the
addition (+) operator, if they aren't there is no need to add a leading zero.
const date = new Date('September 24, 2025 05:24:06'); let seconds = date.getSeconds(); seconds = seconds <= 9 ? '0' + seconds : seconds; console.log(seconds); // 👉️ 06
We used a ternary operator, which is very similar to an if/else statement.
If the seconds are
9 or less, we add a leading zero, otherwise we return the
seconds as is.
I'll send you 1 email a week with links to all of the articles I've written that week