Change getMonth to 2 digits in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Matt Heaton

Change getMonth to 2 digits in JavaScript #

To change the getMonth() method to 2 digits:

  1. Add 1 to the result from calling getMonth() and convert it 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('March 14, 2025 05:24:07'); const month = String(date.getMonth() + 1).padStart(2, '0'); console.log(month); // ๐Ÿ‘‰๏ธ 03

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

Note that we added 1 to the month, this is because the getMonth method returns an integer from 0 (January) to 11 (December).

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 month should always have a length of 2, so that's what we set as a target length.

If the month already has 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('October 24, 2025 12:24:22'); const month = String(date.getMonth() + 1).padStart(2, '0'); console.log(month); // ๐Ÿ‘‰๏ธ 10

The month was set to 10 (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 getMonth() method to 2 digits, check if the month is less than 10, if it is, add a leading zero to the month using the addition (+) operator, if it isn't there is no need to add a leading zero.

index.js
function getMonth2Digits(date) { // ๐Ÿ‘‡๏ธ Add 1, because getMonth is 0-11 const month = date.getMonth() + 1; if (month < 10) { return '0' + month; } return month; } const date1 = new Date('March 14, 2025 05:24:07'); console.log(getMonth2Digits(date1)); // ๐Ÿ‘‰๏ธ 03 const date2 = new Date('December 14, 2025 05:24:07'); console.log(getMonth2Digits(date2)); // ๐Ÿ‘‰๏ธ 12

We created a reusable function that formats a month to 2 digits.

The first thing we have to do is add 1 to the return value of the getMonth method.

If the month is less than 10, we add a leading zero, otherwise we return the month 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