How can I get a list of all long month names using the ECMAScript Internationalization API?
For example, if the user's locale is en-US
, I'd like to get the following:
["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
Intl.DateTimeFormat.prototype.format() Getter function that formats a date according to the locale and formatting options of this DateTimeFormat object. Intl.DateTimeFormat.prototype.formatToParts() Returns an Array of objects representing the date string in parts that can be used for custom locale-aware formatting.
The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.
// Creating a date object var today = new Date('2021-10-06'); // yyyy-mm-dd // Getting short month name (e.g. "Oct") var month = today. toLocaleString('default', { month: 'short' }); console.
This should do it:
function getMonthsForLocale(locale) {
var format = new Intl.DateTimeFormat(locale, { month: 'long' })
var months = []
for (var month = 0; month < 12; month++) {
var testDate = new Date(Date.UTC(2000, month, 1, 0, 0, 0));
months.push(format.format(testDate))
}
return months;
}
/**
* Return list of months
* 🌍 localeName : name of local, f.e. en-GB, default es-MX
* ✅ monthFormat : short, numeric, long (Default)
*/
function monthsForLocale(localeName = 'es-MX', monthFormat = 'long') {
const format = new Intl
.DateTimeFormat(localeName, {month: monthFormat}).format;
return [...Array(12).keys()]
.map((m) => format(new Date(Date.UTC(2021, m))));
}
// testing...
console.log(monthsForLocale());
// return ['diciembre', 'enero', ..., 'noviembre' ]
console.log(monthsForLocale('en-GB', 'numeric'));
// return // ['12', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
console.log(monthsForLocale('en-GB', 'short'));
// // ['Dec', 'Jan', 'Feb','Mar', 'Apr', 'May','Jun', 'Jul', 'Aug','Sep', 'Oct', 'Nov' ]
console.log(monthsForLocale('ja-JP', 'short'));
// // ['12月', '1月', '2月', '3月', '4月', '5月','6月', '7月', '8月','9月', '10月', '11月']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With