How to get month list in your locale
Maksim
Posted on June 4, 2020
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
💖 💪 🙅 🚩
Maksim
Posted on June 4, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.