When working with a JavaScript Date
object instance, you may sometimes need to extract the name of the month. This can be done easily using the toLocaleString()
method, which is part of JavaScript’s internationalization methods.
To obtain the month name in your current locale, you can follow these steps:
- Create a
Date
object:
const today = new Date();
- Use the
toLocaleString()
method with themonth
option set to'long'
:
today.toLocaleString('default', { month: 'long' });
This will return the full month name based on your current locale. For example, if your locale is set to English (US), it will return “October”.
If you prefer the abbreviated month name, you can use the short
format:
today.toLocaleString('default', { month: 'short' });
In this case, it will return “Oct”.
You can also specify a different locale by passing it as the first parameter to toLocaleString()
. For example, using the Italian (Italy) locale (‘it-IT’) will return “ottobre”:
today.toLocaleString('it-IT', { month: 'long' });
By following these steps, you can easily obtain the month name from a JavaScript Date
object instance.