The JavaScript getMonth() method returns the month value from a specified date object as a zero-based integer, ranging from 0 to 11, where 0 represents January and 11 represents December. JavaScript getMonth 2 digits possible using additional code.
You can use the slice() method for this
string.slice(start, end)
JavaScript getMonth 2 digits example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
const date = new Date();
const month = ("0" + (date.getMonth() + 1)).slice(-2)
console.log("Monde 2 Digit: ", month);
</script>
</body>
</html>
Output:
![JavaScript getMonth 2 digits](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2023/04/JavaScript-getMonth-2-digits.jpg?resize=275%2C130&ssl=1)
The slice()
can be used to extract a portion of a string by specifying the starting and ending indices. In this case, using -2
as the argument for slice()
means to start from the second-to-last character (which is the tens digit of the month value) and include the last character (which is the units digit of the month value), effectively extracting the month value with two digits.
Or you can use string manipulation methods such as padStart().
let currentDate = new Date();
let month = currentDate.getMonth() + 1; // Add 1
let monthWithTwoDigits = month.toString().padStart(2, '0');
console.log(monthWithTwoDigits); // Output: '04' (for April)
Do comment if you have any doubts or suggestions on this Js date object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version