umami/src/components/hooks/useTimezone.ts

38 lines
1 KiB
TypeScript
Raw Normal View History

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';
import useStore, { setTimezone } from 'store/app';
const selector = (state: { timezone: string }) => state.timezone;
2023-05-18 06:20:06 +00:00
export function useTimezone() {
const timezone = useStore(selector);
const saveTimezone = (value: string) => {
setItem(TIMEZONE_CONFIG, value);
setTimezone(value);
};
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-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 };
}
2023-05-18 06:20:06 +00:00
export default useTimezone;