If we do this:
const d = new Date('2010-10-20');
console.log(d.getUTCDate());
The console will log 20.
However if we do:
const d = new Date('2010-10-20');
d.setHours(0, 0, 0, 0);
console.log(d.getUTCDate());
Then 19 is logged.
Is this correct? I was expecting 20 still. Thoughts?
Another thing I noticed is when passing in time as all zeroes and then calling getUTCDate() the expected result is logged:
const d3 = new Date('2000-10-20T00:00:00Z');
console.log(`D3: ${d3.getUTCDate()}`);
CodePudding user response:
It is because of the difference between your time zone and UTC, getUTCDate() convert the time to UTC and then get the date of it. try:
const d = Date.UTC(2010, 10, 20, 0,0,0);
console.log(new Date(d).getUTCDate());
Also as @jonrsharpe pointed out in the comments, the real issue is that setHours instead of setUTCHours was called on the constructed date.
when you create a Date it will be created with the time zone from your env, nodejs read it from TZ if it is set in env. you can find the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC) using: getTimezoneOffset()
