彻底解决时间格式化难题:Folo中Day.js的高效应用指南
Folo作为新一代信息浏览器,集成了强大的时间处理功能,其核心依赖Day.js库实现高效时间格式化。本文将详细介绍Folo项目中Day.js的配置方案、实用功能及最佳实践,帮助开发者轻松应对各类时间处理场景。
Folo项目中的Day.js基础配置
Folo在packages/internal/components/src/utils/dayjs.ts中完成Day.js的基础配置,通过插件扩展实现本地化、相对时间等核心功能:
import dayjs from "dayjs" import customParseFormat from "dayjs/plugin/customParseFormat" import duration from "dayjs/plugin/duration" import localizedFormat from "dayjs/plugin/localizedFormat" import relativeTime from "dayjs/plugin/relativeTime" export const initializeDayjs = () => { dayjs.extend(duration) // 支持时间跨度计算 dayjs.extend(relativeTime) // 实现"3小时前"等相对时间表达 dayjs.extend(localizedFormat) // 本地化格式支持 dayjs.extend(customParseFormat) // 自定义解析格式 }多语言时间本地化实现
Folo支持多语言环境下的时间显示,在apps/ssr/client/@types/constants.ts中定义了语言映射关系:
export const dayjsLocaleImportMap = { en: ["en", () => import("dayjs/locale/en")], ["zh-CN"]: ["zh-cn", () => import("dayjs/locale/zh-cn")], ["ja"]: ["ja", () => import("dayjs/locale/ja")], ["zh-TW"]: ["zh-tw", () => import("dayjs/locale/zh-tw")], }在设置面板中,用户可通过apps/desktop/layer/renderer/src/modules/settings/tabs/general.tsx切换语言:
dayjs.locale(value) // 根据用户选择切换Day.js语言环境实用时间处理功能
1. 相对时间格式化
Folo在packages/internal/components/src/ui/datetime/index.tsx中实现了智能时间显示:
// 最近N天内显示相对时间,否则显示具体日期 if (relativeBeforeDay && Math.abs(dayjs(date).diff(new Date(), "d")) > relativeBeforeDay) { return dayjs(date).format(template) } return dayjs.duration(dayjs(date).diff(dayjs(), "minute"), "minute").humanize()实际效果如"3分钟前"、"2小时前"等自然语言表达,增强用户体验。
2. 日期时间选择器
在packages/internal/components/src/ui/input/DateTimePicker.tsx中,Day.js与UI组件结合实现日期选择功能:
const [rangeStart, setRangeStart] = useState<dayjs.Dayjs | null>(() => rangeValue?.start ? dayjs(rangeValue.start) : null, )3. 时间跨度计算
音频播放器模块apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/AudioPlayer.tsx中使用duration插件:
const duration = dayjs.duration(seconds, "seconds")轻松实现音频时长格式化与进度计算。
最佳实践与性能优化
- 按需加载语言包:通过动态import避免一次性加载所有语言包
- 全局初始化:在应用入口
apps/ssr/client/initialize/index.ts调用initializeDayjs()确保全局配置 - 避免重复解析:对频繁使用的时间格式进行缓存处理
- 类型安全:利用TypeScript类型定义确保时间处理类型安全
通过这些实践,Folo项目中的时间处理模块既保持了功能丰富性,又确保了性能高效。无论是内容发布时间显示、任务调度还是用户活动跟踪,Day.js都提供了可靠的时间处理能力,成为Folo作为新一代信息浏览器的重要技术支撑。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考