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

202
Visualizações
JS setDate() not working as expected when Date is created with new Date('YYYY-MM-DD')
let a = new Date() 
a.setDate(1) <--- this set date to the first date of this month.

However

let b = new Date ('2020-02-15')
b.setDate(1)
b.toISOString() -> returns'2020-02-02T00:00:00.000Z' 

What's going on?

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

0

Timezones. The difference comes from the fact that you're initializing date a with the current time, and b at midnight local time, which (depending on the time of day where you are) can be a different day when represented in UTC. setDate() sets the "day" part of the Date object based on your locale.

let a = new Date() 
a.setDate(1);
let b = new Date('2022-02-14');
b.setDate(1);
console.log("UTC:")
console.log(a.toISOString());
console.log(b.toISOString());

console.log('Local timezone:')
console.log(a.toLocaleString())
console.log(b.toLocaleString())

The above code will stop proving its point in about a month, so for the benefit of People Of The Future™ here is the current output:

UTC:
2022-02-01T17:11:37.114Z
2022-02-02T00:00:00.000Z
Local timezone:
2/1/2022, 12:11:37 PM
2/1/2022, 7:00:00 PM
about 4 years ago · Juan Pablo Isaza Relatório

0

I think it have something to do with your TimeZone and Time Settings

date.toISOString() always displays the date as

YYYY-MM-DDTHH:mm:ss.sssZ

Where Z means UTC+0 TimeZone

try adding the the time and the TimeZone when constructing the date

something like

let date = new Date('2020-02-12T00:00:00.000+02:00');
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