Home > Net >  JS setDate() not working as expected when Date is created with new Date('YYYY-MM-DD')
JS setDate() not working as expected when Date is created with new Date('YYYY-MM-DD')

Time:02-05

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?

CodePudding user response:

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

CodePudding user response:

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');
  •  Tags:  
  • Related