Home > Blockchain >  UTC issue on formatting date
UTC issue on formatting date

Time:07-27

enter image description hereI have this react typescript/js code:

   fromDate: fromDate.toISOString().split('T')[0], // formatted to 2000-01-01

but it's not working properly. It changes fromDate to the next day when I run it late at night. So I tried on 6/30/2022 at 11pm and it changed it to 7/1/2022.

My attempted fix is to use date-fns format function:

fromDate: format(Date.parse(fromDate.toLocaleString()), 'yyyy-MM-dd'),// formatted to 2000-01-01

My question is will this resolve the utc issue? Maybe I should rather change the datepicker that gets the fromDate to ignore times?

How can I test it without trying it at 11pm?

This image attached is how it looked in the console when I console logged the problem: The top line is console.log(fromDate). The bottom line is console.log(fromDate.toISOString().split('T')[0])

CodePudding user response:

Format will not solve your UTC issue, you need to pass a timezone to toLocaleString yourself.

Rather than parsing the date yourself, you could also pass arguments to toLocaleString in order to choose a time zone and a format.

For instance:

const event = new Date();
let options = { year: 'numeric', month: 'numeric', day: 'numeric',timeZone: 'EST' };
console.log(event.toLocaleString('en-US', options));

You can even pass an option for weekday: 'long' to tell toLocaleString to print out the actual name of a weekday.

As @derpirscher pointed out in the comments, since you are looking for yyyy-MM-dd formatting, the best approach will likely be to pass a timezone yourself and then parse the date as you have been doing:

format(Date.parse(fromDate.toLocaleString('en-US')), 'yyyy-MM-dd')

See these docs

CodePudding user response:

testing was easy!

const test = new Date('Thu june 30 2022 23:03:00 GMT-0400');
console.log(test.toISOString().split('T')[0]);
console.log(format(Date.parse(test.toLocaleString()), 'yyyy-MM-dd'))

1st console.log shows problem 2nd console.log shows fixed problem.

  • Related