2024-03-29 23:04:39 +00:00
|
|
|
import { setItem } from 'next-basics';
|
2020-09-30 23:27:27 +00:00
|
|
|
import { TIMEZONE_CONFIG } from 'lib/constants';
|
2024-08-16 07:35:08 +00:00
|
|
|
import { formatInTimeZone, zonedTimeToUtc, utcToZonedTime } from 'date-fns-tz';
|
2024-03-29 23:04:39 +00:00
|
|
|
import useStore, { setTimezone } from 'store/app';
|
|
|
|
|
|
|
|
|
|
const selector = (state: { timezone: string }) => state.timezone;
|
2020-09-19 17:35:05 +00:00
|
|
|
|
2023-05-18 06:20:06 +00:00
|
|
|
export function useTimezone() {
|
2024-03-29 23:04:39 +00:00
|
|
|
const timezone = useStore(selector);
|
2020-09-19 17:35:05 +00:00
|
|
|
|
2024-03-29 23:04:39 +00:00
|
|
|
const saveTimezone = (value: string) => {
|
|
|
|
|
setItem(TIMEZONE_CONFIG, value);
|
|
|
|
|
setTimezone(value);
|
|
|
|
|
};
|
2020-09-19 17:35:05 +00:00
|
|
|
|
2024-08-13 07:40:19 +00:00
|
|
|
const formatDate = (date: string, pattern: string) => {
|
2024-08-13 07:56:41 +00:00
|
|
|
return formatInTimeZone(
|
|
|
|
|
/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$/.test(date)
|
|
|
|
|
? date
|
|
|
|
|
: date.split(' ').join('T') + 'Z',
|
|
|
|
|
timezone,
|
|
|
|
|
pattern,
|
|
|
|
|
);
|
2024-08-13 07:40:19 +00:00
|
|
|
};
|
|
|
|
|
|
2024-08-16 07:35:08 +00:00
|
|
|
const toUtc = (date: Date | string | number) => {
|
|
|
|
|
return zonedTimeToUtc(date, timezone);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const fromUtc = (date: Date | string | number) => {
|
|
|
|
|
return utcToZonedTime(date, timezone);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return { timezone, saveTimezone, formatDate, toUtc, fromUtc };
|
2020-09-19 17:35:05 +00:00
|
|
|
}
|
2023-05-18 06:20:06 +00:00
|
|
|
|
|
|
|
|
export default useTimezone;
|