Borislav Hadzhiev
Last updated: Oct 23, 2021
Check out my new book
To change the getDate()
method to 2 digit format:
getDate()
to a string.padStart()
method to add a leading zero if it's necessary.padStart
method allows us to add a leading zero to the start of the
string.const date = new Date('April 04, 2025 05:24:07'); const day = String(date.getDate()).padStart(2, '0'); console.log(day); // 👉️ 04
The padStart method has to be used on a string, so the first step is to convert the day of the month to a string.
We passed the following 2 parameters to the padStart
method:
padStart
method should
return, once it has been padded.0
.We know that the days should always have a length of 2
, so that's what we set
as a target length.
padStart
method would not add an additional leading zero because we've set the target length
to 2
.const date = new Date('March 24, 2025 12:24:22'); const day = String(date.getDate()).padStart(2, '0'); console.log(day); // 👉️ 24
The day of the month is 24
(2 digits), so the padStart
method didn't add a
leading zero.
padStart
method is not supported in Internet Explorer. If you have to support the browser, use the next approach covered in this article.To change the getDate()
method to 2 digits, check if the day of the month
returns 9
or less, if so, add a leading zero to the day using the addition (+)
operator.
const date = new Date('April 07, 2025 10:24:06'); let day = date.getDate(); day = day <= 9 ? '0' + day : day; console.log(day); // 👉️ 07
We used a ternary operator, which is very similar to an if/else statement.
If the day of the month is 9
or less, we add a leading zero, otherwise we
return the day.