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

199
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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