In JavaScript, you can get the current month with a leading zero by using the getMonth()
method of the Date
object and concatenating a ‘0’ to the front of the result if the month is less than 10.
To get the current month in JavaScript with a leading zero (i.e., “05” for May), you can use the toLocaleString
method with the en-US
locale and the month
option set to "2-digit"
.
const now = new Date();
const month = (now.toLocaleString("en-US", { month: "2-digit" }));
console.log(month);
Or you can use the getMonth()
method with padStart()
method to add a leading zero if the month value is less than 10.
const now = new Date();
const month = (now.getMonth() + 1).toString().padStart(2, "0");
console.log(month);
JavaScript gets a month with a leading 0 example
A simple example code gets the current month with a leading zero using both the toLocaleString
and getMonth
methods:
<!DOCTYPE html>
<html>
<head>
<script>
// Using the toLocaleString method
const now = new Date();
const month1 = now.toLocaleString('en-US', { month: '2-digit' });
console.log(month1);
// Using the getMonth and padStart methods
const month2 = (now.getMonth() + 1).toString().padStart(2, '0');
console.log(month2);
</script>
</head>
<body>
</body>
</html>
Output:
Comment if you have any doubts or suggestions on this JS date topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version