More on Date Conversions
Nov 15,
I was recently working on an app where the user was entering one date, but the date was turning into something else. I hate it when this happens, and even had similar issues in the early versions of my Learn With book series. Usually this is a conversion issue between date entry in the UI, storage in backend service, and sending that data back to the UI.
It drove me nuts, and I finally found a solution. I decided to store all dates in UTC format, and pass them on to the users in the same.
When the user enters a date in the UI, you can turn it into UTC Format using the JS toISOString() function:
2let isoString = originalDate.toISOString()
3console.log(isoString);
You should see something like this in your console:
2022-11-09T14:41:56.202Z
Now send this to your backend, and save it in your database as a date. All good!
When your REST Services send that date string back to the UI, you can re-convert it into a date object for display:
2console.log(dateObject);
The output should be something like this:
I found this to be a great way to handle dates between the front end and backend of an application.