How do I correctly calculate the last day of every month in Javascript?
Follow below my thought process in code to calculate the last day of July 2021.
let tzoffset = new Date().getTimezoneOffset() * 60000;
//### Calculates the TIME at which today started
let todayStartedAt = new Date(new Date().setHours(0,0,0,0) - tzoffset );
console.log('Today Started At: ' +todayStartedAt.toISOString());
//### Calculates the first day/date TWO months ago
let twoMonthsAgo = todayStartedAt;
twoMonthsAgo.setMonth(todayStartedAt.getMonth() - 2);
twoMonthsAgo.setDate(twoMonthsAgo.getDate() - twoMonthsAgo.getDate() + 1 );
console.log('The first day 2 Months Ago was on: ' +twoMonthsAgo.toISOString());
var month = twoMonthsAgo.getMonth(); // July = 6
let year = twoMonthsAgo.getFullYear(); // 2021
//### Calculates the LAST day/date TWO months ago
var theLastDayTwoMonthsAgo = new Date(twoMonthsAgo.getFullYear(), twoMonthsAgo.getMonth() +1, 0);
console.log("The Last Day Two Months Ago was: " +theLastDayTwoMonthsAgo.toISOString() );
The code above yields:
Today Started At: 2021-09-09T00:00:00.000Z
The first day 2 Months Ago was on: 2021-07-01T00:00:00.000Z
The Last Day Two Months Ago was: 2021-07-30T21:00:00.000Z
Kindly NOTE that the results for The Last Day Two Months Ago
is ERRONEOUS, as the last day in July does NOT
end on the 30th of July, but rather the 31st of July.
Secondly, note that the time part of the date is: T21:00:00.000Z
how do I alter this to read T23:59:59.000Z