Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of month names in javascript using Intl

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"]
like image 948
mark Avatar asked Nov 10 '17 23:11

mark


People also ask

What is Intl DateTimeFormat ()?

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.

What is Intl JavaScript?

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.

How to get month short in JavaScript?

// 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.


2 Answers

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;
}
like image 154
John Ellmore Avatar answered Nov 03 '22 00:11

John Ellmore


My solution in 2021 with es6 Syntax

/**
 * 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月']
like image 21
fitorec Avatar answered Nov 03 '22 00:11

fitorec