Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading