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:

view plain print about
1let originalDate = new Date();
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:

view plain print about
1let dateObject = new Date(isoString);
2console.log(dateObject);

The output should be something like this:

view plain print about
1Wed Nov 09 2022 09:41:56 GMT-0500 (Eastern Standard Time)

I found this to be a great way to handle dates between the front end and backend of an application.

Play with a Plunker here