1

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

SirBT
  • 1,580
  • 5
  • 22
  • 51
  • `twoMonthsAgo.getDate() - twoMonthsAgo.getDate() + 1` is `1` btw. –  Sep 09 '21 at 09:02
  • `new Date(new Date().setHours(0,0,0,0) - tzoffset );` will return an incorrect result if it's called after the daylight saving change over time on the day of change. Anyway, `new Date(new Date().setUTCHours(0,0,0,0))` does the job in less code (though creating two Date objects rather than one is likely not performant and `let d = new Date(); d.setUTCHours(0,0,0,0)` is less code). :-) – RobG Sep 09 '21 at 09:30

1 Answers1

2

You can use the setDate() with value of 0 (Zero).

Example:

let august=new Date(2021,7,1); //Take first day of august, to find last day of July
august.setDate(0); // This is now the last day of July

For example, if 0 is provided for dayValue, the date will be set to the last day of the previous month.

From here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate

Igal S.
  • 13,146
  • 5
  • 30
  • 48