Change getHours to 2 digits in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Hannah Busing

Change getHours to 2 digits in JavaScript #

To change the getHours() method to 2 digits:

  1. Convert the result from calling getHours() to a string.
  2. Use the padStart() method to add a leading zero if it's necessary.
  3. The padStart method allows us to add a leading zero to the start of the string until it reaches a specified target length.
index.js
const date = new Date('September 24, 2025 05:24:00'); const hours = String(date.getHours()).padStart(2, '0'); console.log(hours); // ๐Ÿ‘‰๏ธ 05

The padStart method has to be used on a string, so the first step is to convert the number of hours to a string.

We passed the following 2 parameters to the padStart method:

  1. target length - the length of the string the padStart method should return, once it has been padded.
  2. pad string - the string we want to pad our existing string with, in our case - 0.

We know that the hours should always have a length of 2, so that's what we set as a target length.

If the hours already have 2 digits, the padStart method would not add an additional leading zero, because we've set the target length to 2.
index.js
const date = new Date('September 24, 2025 15:24:00'); const hours = String(date.getHours()).padStart(2, '0'); console.log(hours); // ๐Ÿ‘‰๏ธ 15

The hours were already set to 15 (2 digits), so the padStart method didn't add a leading zero.

The 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 getHours() method to 2 digits, check if the hours are less than or equal to 9, if they are, add a leading zero to the hours using the addition (+) operator, if they aren't there is no need to add a leading zero.

index.js
const date = new Date('September 24, 2025 05:24:00'); let hours = date.getHours(); hours = hours <= 9 ? '0' + hours : hours; console.log(hours); // ๐Ÿ‘‰๏ธ 05

We used a ternary operator, which is very similar to an if/else statement.

If the hours are 9 or less, we add a leading zero, otherwise we leave the hours as is.

Either approach works just fine, if you have to support Internet Explorer, pick the second one.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee