DEV Community

Discussion on: How to get month list in your locale

Collapse
 
umutakyol profile image
asdsadasf

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, lol?

Collapse
 
pretaporter profile image
Maksim

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);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dannyengelman profile image
Danny Engelman • Edited

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);
}

```

`
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
dannyengelman profile image
Danny Engelman • Edited

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))
  );
```

`
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
pretaporter profile image
Maksim

Cool, thanks!

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