Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
How do I calculate the last day of any month in Javascript?

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda