JavaScript - Get Month Name from Date
Find out how to get the name of the month from JavaScript Date object using toLocaleString method andd Intl.DateTimeFormat object.
In this post, we will see how to get the string value of the month name from the JavaScript Date object instance.
In JavaScript, we get the getMonth() method to get the month from JavaScript Date Object Instance.
However, it only returns the index of the month starting from 0 and not the actual alphabetic name of the month.
So, to get the month name from JavaScript Date:
- Use
toLocaleString()method. - Use
Intl.DateTimeFormatObject
Now, let's see how to get the month name with an example in JavaScript.
Use toLocaleStirng() method to get the month name
To get the month name, we can use the toLocaleString() method in JavaScript. It returns a string with language-sensitive representation of the Date Object.
The default language depends on the local setup of your computer.
Now, let's use the method to get the month.
const date = new Date() const month_name = date.toLocaleString('default', {month:'long'}) console.log(month_name)
Output:
August
We can also use the short format like this:
date.toLocaleString('default', {month:'short'}) // Aug
Using the Intl.DateTimeFormat Object
We can also use the Intl.dateTimeFormat method to get the name of the month from the Date.
It provides a format() function where we pass the date object and it returns converted language-sensitive data-time formats.
const date = new Date(); const month = new Intl.DateTimeFormat('en-US', {month: "long"}).format(date); console.log(month) // August
Here again, we can use the short format like this:
new Intl.DateTimeFormat('en-US', {month: "short"}).format(date); // Aug
Conclusion: This is how we can get the month name from Javascript date using the toLocaleStirng() method and Intl.DateTimeFormat object.
Related Topics:
Get Tomorrow's Date using JavaScript - Quick Way
Get Current Date in Different Date Formats in JavaScript
Related Posts
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
in vs hasOwnProperty(): Differences in Inherited Properties
The article explains the differences between JavaScript's 'in' operator and 'hasOwnProperty()' method. And also learn the use cases of both in JS.
How to Fix "ReferenceError: document is not defined" in JavaScript
The "ReferenceError: document is not defined" is a common error in JavaScript that occurs when trying to access the `document` object in a non-browser environment like Node.js.
How to Fix the "Cannot Read Property of Undefined" Error in JavaScript
The "Cannot read property of undefined" error occurs when you try to access a property or method of a variable that is undefined in JavaScript.
