last day of all months in typescript

One way to get the last day of all months in TypeScript is by creating a loop that goes through all 12 months and uses the Date constructor to create a new date object at the start of the next month (with the day set to 0), and then retrieves the day of the month from that date object (which will be the last day of the current month).

index.ts
const lastDaysOfMonth: number[] = [];

for (let month = 1; month <= 12; month++) {
  const date = new Date(new Date().getFullYear(), month, 0);
  const lastDayOfMonth = date.getDate();
  lastDaysOfMonth.push(lastDayOfMonth);
}

console.log(lastDaysOfMonth);
258 chars
10 lines

In this code, we first create an empty array lastDaysOfMonth using the Array constructor.

Then we use a for loop to go through all 12 months, starting from 1 (January) and ending at 12 (December).

Inside the loop, we create a new date object using the Date constructor, passing in the current year (new Date().getFullYear()) and the next month (month + 1) as arguments, and setting the day to 0. The reason we set the day to 0 is because when you set the day to 1, the date object will be set to the first day of that month, so setting the day to 0 automatically sets it to the last day of the previous month.

We then use the getDate() method to retrieve the day of the month from the date object, which will be the last day of the current month. This value is then pushed into the lastDaysOfMonth array using the push() method.

Finally, the lastDaysOfMonth array is logged to the console, which will output an array with the last day of each month in the current year.

gistlibby LogSnag