Skip to content

JavaScript getMonth 2 digits

  • by

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

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

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading