You can use localization formatting:
const DAYS_IN_WEEK = 7;
const MONTHS_IN_YEAR = 12;
function localizedWeekdayNames(
locale: Intl.LocalesArgument = "default",
dateStyle: Intl.RelativeTimeFormatStyle = "short"
): string[] {
const dayNames: string[] = [];
const currentDate = new Date();
while (currentDate.getDay() !== 0) {
currentDate.setDate(currentDate.getDate() + 1);
}
for (let day = 0; day < DAYS_IN_WEEK; day++) {
dayNames.push(
currentDate.toLocaleDateString(locale, { weekday: dateStyle })
);
currentDate.setDate(currentDate.getDate() + 1);
}
return dayNames;
}
function localizedMonthNames(
locale: Intl.LocalesArgument = "default",
dateStyle: Intl.RelativeTimeFormatStyle = "short"
): string[] {
const monthNames: string[] = [];
const currentDate = new Date();
while (currentDate.getMonth() !== 0) {
currentDate.setMonth(currentDate.getMonth() + 1);
}
for (let month = 0; month < MONTHS_IN_YEAR; month++) {
monthNames.push(
currentDate.toLocaleDateString(locale, { month: dateStyle })
);
currentDate.setMonth(currentDate.getMonth() + 1);
}
return monthNames;
}
// ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
console.log(localizedWeekdayNames());
// ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
console.log(localizedMonthNames());
Here is the generated JS with some additional localization output.
const DAYS_IN_WEEK = 7;
const MONTHS_IN_YEAR = 12;
function localizedWeekdayNames(locale = "default", dateStyle = "short") {
const dayNames = [];
const currentDate = new Date();
while (currentDate.getDay() !== 0) {
currentDate.setDate(currentDate.getDate() + 1);
}
for (let day = 0; day < DAYS_IN_WEEK; day++) {
dayNames.push(currentDate.toLocaleDateString(locale, {
weekday: dateStyle
}));
currentDate.setDate(currentDate.getDate() + 1);
}
return dayNames;
}
function localizedMonthNames(locale = "default", dateStyle = "short") {
const monthNames = [];
const currentDate = new Date();
while (currentDate.getMonth() !== 0) {
currentDate.setMonth(currentDate.getMonth() + 1);
}
for (let month = 0; month < MONTHS_IN_YEAR; month++) {
monthNames.push(currentDate.toLocaleDateString(locale, {
month: dateStyle
}));
currentDate.setMonth(currentDate.getMonth() + 1);
}
return monthNames;
}
// Sun Mon Tue Wed Thu Fri Sat
console.log(...localizedWeekdayNames());
// Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
console.log(...localizedMonthNames());
// domingo lunes martes miércoles jueves viernes sábado
console.log(...localizedWeekdayNames('es-ES', 'long'));
// enero febrero marzo abril mayo junio
// julio agosto septiembre octubre noviembre diciembre
console.log(...localizedMonthNames('es-ES', 'long'));
new Date(2020, monthIndex, 1).toLocaleString("en-us", {month: "long"});
– Easton