Hi there! I am glad to show simple TypeScript function, that maybe will save your time. In many cases you need to implement selector of months. In some cases it should be in different locales. See it below:
function getMonthList(
locales?: string | string[],
format: "long" | "short" = "long"
): string[] {
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: number) =>
formatter.format(new Date(year, monthIndex));
return monthList.map(getMonthName);
}
That's it. Just provide your locale as param.
For example, 🇬🇧 getMonthList('en')
will return:
January
February
March
April
May
June
July
August
September
October
November
December
Try it by yourself on codesandbox.
For short version of names just provide second param as short
.
For example, 🇬🇧 getMonthList('en', 'short')
will return:
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
Follow me in Twitter
Update
By your requests I have extracted function in package
Top comments (9)
Thanks, fixed
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?
Thank you! JavaScript version:
Using the 2nd parameter mapFn on Array.from instead of .map saves a spread on monthList
And since year is not a parameter, no need for
const year
declaration to get a monthnamenew Date(0, monthIndex)
will do, for ES Arrow function:Cool, thanks!
For constructor of Intl.DateTimeFormat
locales
is optional param. No requirement to provide default value oflocale
.Sorry I know this is a bit of an old thread but I can't find an answer via google. Could someone please explain line 8 of Danny Engleman's 2nd post.
I get that it is creating an object as the 2nd parameter to "DateTimeFormat" with 1 attribute named "month" that maps to another object.
What does [notation[0]] || "long" do? To me it looks like it should be a 2nd attribute of the outer object, but in my mind it should have a comma.
Thank you in advance.
Never mind. I got it.
Amazing work!