EN
TypeScript - day name for the first day of month
0 points
In this article, we would like to show you how to get the first day name of the indicated month in TypeScript.
Quick solution:
xxxxxxxxxx
1
const days: string[] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
2
3
const year: number = 2021;
4
const month: number = 7; // 0 - January, ..., 7 - August, ..., 11 - December
5
const date: Date = new Date(year, month, 1);
6
const day: string = days[date.getDay()];
7
8
console.log(day); // Sunday
Where in the above code, we:
- use an array with names of the weekdays,
- create a date that represents the first day in the month - it is
Date(year, month, 1)
, - get day index in the week using
getDay()
method - it counts days from0
to6
, staring from Sunday, - get the day name from the array using the day index.
xxxxxxxxxx
1
const days: string[] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
2
3
const getFirstDayName = (year: number, month: number): string => {
4
const date = new Date(year, month, 1); // first day of the month
5
return days[date.getDay()]; // getting day of the week (counted from 0 to 6 - Sunday as first)
6
};
7
8
9
// Usage example:
10
11
console.log(getFirstDayName(2021, 0)); // Friday // 0 - January
12
console.log(getFirstDayName(2021, 1)); // Monday // 1 - February
13
console.log(getFirstDayName(2021, 2)); // Monday // 2 - March
Output:
xxxxxxxxxx
1
Friday
2
Monday
3
Monday