I would suggest using UTC times to communicate dates from the frontend to the backend. They are unambiguous and will not depend on what timezone the user is in.
You can either use Unix time, the number of seconds / milliseconds since 1 January 1970 00:00 UTC, e.g. 1635494392
or ISO 8601, a well-defined string encoding of date and time, e.g. 2021-10-29T08:27:22Z
.
I recommend using ISO 8601 dates since they're much easier to eyeball than unix dates. They're also supported by native JS date objects and all time/date libraries.
If you send a date like 2021-10-29T08:27:22Z
to the backend, it won't need to be converted to UTC and no ambiguity exists.
Likewise, when the frontend receives a date from the backend, using an ISO UTC date will mean the date will be parsed and understood unambiguously.
It's also easy to convert to local time, using Date.toLocaleString()
for example. This will display in the user's local timezone by default, but you can display in any timezone using the argument { timeZone: 'xxx' }.
For example:
const timestampFromBackend = '2021-10-29T08:27:22Z';
const dateFromBackend = new Date(timestampFromBackend);
console.log('Date from backend (UTC):', dateFromBackend.toLocaleString([], { timeZone: 'UTC'}));
console.log('Date from backend (local):', dateFromBackend.toLocaleString());
// We can display in any timezone if we wish
console.log('Date from backend (Pacific Time):', dateFromBackend.toLocaleString([], { timeZone: 'America/Los_Angeles'}));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Likewise, we can always convert a frontend date to an ISO UTC date, using Date.toISOString():
const frontEndDate = new Date();
const dateToBackend = frontEndDate.toISOString();
console.log('frontEndDate:', frontEndDate.toString() );
console.log('ISO string to send to backend:',dateToBackend);
.as-console-wrapper { max-height: 100% !important; top: 0; }