Files
gsfdc/demo-dify/dify/web/hooks/use-timestamp.ts
T
wuzilongandCursor 6519682885 chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 13:59:25 +08:00

62 lines
1.8 KiB
TypeScript

'use client'
import { useQuery } from '@tanstack/react-query'
import dayjs from 'dayjs'
import timezone from 'dayjs/plugin/timezone'
import utc from 'dayjs/plugin/utc'
import { useCallback } from 'react'
import { useLocale } from '#i18n'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { formatToLocalTime } from '@/utils/format'
dayjs.extend(utc)
dayjs.extend(timezone)
type UseTimestampOptions = {
timezone?: string
}
const getBrowserTimezone = () => {
return new Intl.DateTimeFormat().resolvedOptions().timeZone
}
const getIntlLocale = (locale: string) => locale.replace('_', '-')
const useTimestamp = ({ timezone: timezoneOverride }: UseTimestampOptions = {}) => {
const locale = useLocale()
const { data: accountTimezone } = useQuery({
...userProfileQueryOptions(),
select: (data) => data.profile.timezone ?? undefined,
enabled: timezoneOverride === undefined,
})
const resolvedTimezone = timezoneOverride ?? accountTimezone ?? getBrowserTimezone()
const formatTime = useCallback(
(value: number, format: string) => {
return formatToLocalTime(dayjs.unix(value).tz(resolvedTimezone), locale, format)
},
[locale, resolvedTimezone],
)
const formatDate = useCallback(
(value: string, format: string) => {
return formatToLocalTime(dayjs(value).tz(resolvedTimezone), locale, format)
},
[locale, resolvedTimezone],
)
const formatMonthDay = useCallback(
(value: number) => {
return new Intl.DateTimeFormat(getIntlLocale(locale), {
month: 'short',
day: 'numeric',
timeZone: resolvedTimezone,
}).format(value * 1000)
},
[locale, resolvedTimezone],
)
return { formatTime, formatDate, formatMonthDay }
}
export default useTimestamp