How to get month name from a date in JavaScript?
There can be many scenarios when you need to print the month name from a Date
object while coding in JavaScript, let’s see how we can find the easiest solution to that problem.
To get the month name, we can use the built-in toLocaleDateString()
method from the Date
object.
toLocaleDateString()
method takes two parameters, they’re locales
and options
, respectively.
In the first parameter locales
, we can give “default” as an argument, but the important part is the second parameter, the options
object. The options
object can take many properties but the one we’re looking for is the month
property.
We can get the month name in two formats, one is the full month name (ex. November) and the other is a 3 letter short form (ex. Nov).
To get the full month name, we use "long"
as the value for the month
property and to get the month name in short format, we use the "short"
as the value for the month
property.
Let’s see the code below:
const date = new Date();
// To get the full month name
console.log(date.toLocaleDateString("default", { month: "long" })); // February
// To get the month name with first three letters (ex. Jan or Oct)
console.log(date.toLocaleDateString("default", { month: "short" })); // Feb