Date Formatting 技能制定了在 OneKey 各类应用中统一处理日期与时间格式化的规范。
一、核心规则 禁止使用原生 JavaScript 日期方法,包括:date.toLocaleDateString()、date.toLocaleString()、date.toISOString()、new Intl.DateTimeFormat().format(date)。 正确做法是从 @onekeyhq/shared/src/utils/dateUtils 导入并使用封装好的函数,例如: import { formatDate } from '@onekeyhq/shared/src/utils/dateUtils'; formatDate(date, { hideSeconds: true });
二、函数速查 技能给出了常用函数及其用途与示例输出:
- formatDate(date, options?):完整日期与时间,示例输出 2024/01/15, 14:30
- formatTime(date, options?):仅时间,示例输出 14:30:45
- formatRelativeDate(date):相对显示,如 Today、Yesterday
- formatDistanceToNow(date):时间距离,如 2 hours ago
- formatDateFns(date, format?):自定义格式,基于模板
三、常见模式
- 交易历史:使用 formatDate(item.createdAt, { hideTheYear: true, hideSeconds: true }),即在当前年份时隐藏年份,并隐藏秒。
- 自定义格式:使用 formatTemplate,例如 formatDate(item.timestamp, { formatTemplate: 'yyyy-LL-dd HH:mm' })。
- React Hook(用于动态更新):从 @onekeyhq/kit/src/hooks/useFormatDate 导入 useFormatDate,在组件内获取 formatDate 并使用。
四、格式化选项(IFormatDateOptions)
- hideYear?: boolean; 始终隐藏年份
- hideMonth?: boolean; 始终隐藏月份
- hideTheYear?: boolean; 若是当前年份则隐藏年份
- hideTheMonth?: boolean; 若是当前月份则隐藏月份
- hideTimeForever?: boolean; 隐藏时间部分
- hideSeconds?: boolean; 隐藏秒(显示为 HH:mm)
- formatTemplate?: string; 自定义 date-fns 格式
五、详细指南与关键文件 详细规则与示例见 date-formatting.md,涵盖:来自 @onekeyhq/shared/src/utils/dateUtils 的核心工具、可用格式化函数、选项参考与格式模板、交易与历史及相对时间的常见模式、用于动态更新的 React Hook、区域感知格式化、真实示例与故障排查。 关键文件路径:核心工具 packages/shared/src/utils/dateUtils.ts;React Hook packages/kit/src/hooks/useFormatDate.ts;区域映射 packages/shared/src/locale/dateLocaleMap.ts。
六、相关技能 /1k-i18n 国际化与区域处理;/1k-coding-patterns 通用编码模式。