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 date format gives -1 day

I want to format my date with toIsoString function but the function returns -1 day how to fix it? the event.value format is Tue Apr 19 2022 00:00:00 GMT+0400 (Armenia Standard Time)

 console.log(new Date(event.value).toISOString().slice(0,10))

in the console, I’m getting this one 2022-04-18 how you can see the result was -1 day

  startDateChange(event: any): void{
    this.firstDayOfMonth = event;
    console.log(new Date(event.value).toISOString().slice(0, 10));
  }

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 :

This is because of your timezone settings. The toISOString is always returning +0000 while you work with +0400 in your timezone. This essentially withdraws 4 hours resulting in the day before, 20:00 hours.

You could try to fix this by setting the timezone offset to 0 by adding a Z to the date as shown in the second example.

The third example is a safe way to do it but you need to prefix the 0 if you need that.

Another alternative would be to use a date-library like Moment.js, although moment is deprecated (I don’t know for sure what the best alternative would be, that’s up to you).

// Your example (this might work for some people that are in the +0000 timezone)
console.log(new Date('2021-03-03T00:00:00').toISOString().slice(0,10));

// Second example
console.log(new Date('2021-03-03T00:00:00z').toISOString().slice(0,10));

// Third example
const date = new Date('2021-03-03T00:00:00');
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();

console.log(`${year}-${month}-${day}`);
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