Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!