loading...

re: How to get month list in your locale VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Hi, great article, thanks. Which part of this code is typescript, It's like all javascript to me, but some parts seems strange. Maybe those parts...
 

Thank you! JavaScript version:

function getMonthList(locales, format = "long") {
  const year = new Date().getFullYear(); // 2020
  const monthList = [...Array(12).keys()]; // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
  const formatter = new Intl.DateTimeFormat(locales, {
    month: format
  });

  const getMonthName = (monthIndex) =>
    formatter.format(new Date(year, monthIndex));

  return monthList.map(getMonthName);
}
 

Using the 2nd parameter mapFn on Array.from instead of .map saves a spread on monthList

function getMonthList(locales, format = "long") {
  const year = new Date().getFullYear(); // 2020
  const monthList = Array(12).keys(); // an Array Iterator
  const formatter = new Intl.DateTimeFormat(locales, {
    month: format
  });
  const getMonthName = (monthIndex) =>  formatter.format(new Date(year, monthIndex));

  return Array.from(monthList , getMonthName);
}


`

And since year is not a parameter, no need for const year declaration to get a monthname

new Date(0, monthIndex) will do, for ES Arrow function:

const getMonthList = (locale = "en", notation = "long" ) =>
  Array.from(
    Array(12).keys(),
    key => Intl.DateTimeFormat(locale, {
      month: {
         s : "short",
         n : "numeric"
      } [notation[0]] || "long"
    })
    .format(new Date(0, key))
  );


`

Cool, thanks!

For constructor of Intl.DateTimeFormat locales is optional param. No requirement to provide default value of locale.

Code of Conduct Report abuse