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

236
Visualizações
How to get last day of previous month using current date?

I'm trying to get the last of day of previous month using the current date:

var myDate = new Date();

According to MDN:

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

But when set date to zero:

myDate.setDate(0)
console.log(JSON.stringify(myDate));

I get "2021-08-01T01:18:34.021Z" which first day of the current month. What is wrong with this approach?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

JSON.stringify() is serializing the timestamp with a Z timezone, indicating UTC. The difference between UTC and your local timezone is causing the date to rollover to the next day.

You can use toLocaleString() to print the date in your local timezone:

var myDate = new Date();
myDate.setDate(0);
console.log(myDate.toLocaleString());

about 4 years ago · Juan Pablo Isaza Relatório

0

I would use dateInstance.toString() or dateInstance.toLocaleString():

const myDate = new Date;
myDate.setDate(0); myDate.setHours(0, 0, 0, 0);
console.log(myDate.toString()); console.log(myDate.toLocaleString());

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use date-fns package

var df = require("date-fns")

let myDate = new Date() //Thu Aug 05 2021 22:16:09

let lastDayOfPrevMonth = df.endOfMonth(df.subMonths(myDate, 1)) //Sat Jul 31 2021 23:59:59 GMT-0400
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