Learn how to extract the month and year values from a date in JavaScript using the Date
object. Use the getMonth()
and getFullYear()
methods to get the month and year values respectively.
You can get the month and year from a date in JavaScript using the following syntax:
const date = new Date('2023-05-05');
const month = date.getMonth() + 1;
const year = date.getFullYear();
We then use the getMonth()
method to get the month value, adding 1 to the result because getMonth()
returns a 0-indexed value. We also use the getFullYear()
method to get the year value.
Get month and year from date JavaScript example
A simple example code demonstrates how to get the month and year from a date in JavaScript:
<!DOCTYPE html>
<html>
<head>
<script>
const date = new Date('2023-05-05');
const month = date.getMonth() + 1;
const year = date.getFullYear();
console.log('Month:', month);
console.log('Year:', year);
</script>
</head>
<body>
</body>
</html>
Output:
here’s a practical example that uses the Date
object to get the current month and year, and then uses these values to construct a string with the format “MM/YYYY”:
const currentDate = new Date();
const currentMonth = currentDate.getMonth() + 1;
const currentYear = currentDate.getFullYear();
const monthYearString = `${currentMonth.toString().padStart(2, '0')}/${currentYear.toString()}`;
console.log('Current Month/Year:', monthYearString);
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