Skip to content
Advertisement

UTC issue on formatting date

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])

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement