Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda