Sometimes, we want to get month in mm format in JavaScript.
In this article, we’ll look at how to get month in mm format in JavaScript.
How to get month in mm format in JavaScript?
To get month in mm format in JavaScript, we can use the date’s getMonth
and string’s padStart
methods.
For instance, we write:
const mm = (new Date(2022, 1, 1).getMonth() + 1).toString().padStart(2, '0')
console.log(mm)
to create a new date set to Feb 1, 2022.
We get the month number from the date with getMonth
And we add 1 to it to convert it to a human readable month number.
Then we call toString
to convert it to a string.
And then we all padStart
with 2 and '0'
to prepend 0’s to the string until it has length 2.
Therefore, mm
is '02'
.
Conclusion
To get month in mm format in JavaScript, we can use the date’s getMonth
and string’s padStart
methods.