Let’s suppose i have a user who submitted a date in database like this: 2023-04-11T14:50||America/Managua. How may i be able to display the date that is coming from database based on each user’s timezone. Knowing that i already know its timezone.
I am using Javascript and React. This is my submit function.
const handleOnBlur = useCallback(async (e, dirty) => {
e.preventDefault();
if (dirty) {
if (test?.timeZone) {
console.log(test.timeZone);
const dateWithTimeZone = new Date(e.target.value); // Date object with local timezone
const dateWithUTC = dateWithTimeZone.toISOString();
await formValueSubmit(`${dateWithUTC}||${test.timeZone}`);
} else {
console.log('Timezone not available');
}
}
}, [formValueSubmit, test]);
2
Answers
You will need to calculate the offset based on the stored time zone to get the UTC date. Now, you can format the date in a user’s local timezone.
The America/Managua timezone has an offset of -6:00 hours or -360 minutes. The
getOffset
function below correctly calculates -360 as the offset. It is the same offset as Central Standard Time (CST).Note: Usually we add the offset to the date, but since we are parsing a stored time-zoned date, we need to subtract the offset. In this case, we are adding 360 minutes to the Zulu date.
It does not require any additional libraries. It uses built-in
Intl.DateTimeFormat
library.Output
As pointed out here, Javascript is able to convert from UTC to date and time for a given time zone, but not vice versa. You can use a date/time library for that or a "bisection method" like the following.
The
stringify
function uses the Hungarian locale to produce the formatYYYY. MM. DD. HH:MM:SS
, which can be lexicographically compared to the given local time.