effect-smol DateTime模块:彻底告别new Date的坑
【免费下载链接】effect-smolCore libraries and experimental work for Effect v4项目地址: https://gitcode.com/GitHub_Trending/ef/effect-smol
在 effect-smol(Effect v4 核心库仓库)中,DateTime模块为 JavaScript/TypeScript 提供了安全解析、时区感知、可测试、不可变的日期时间方案,帮你彻底告别new Date带来的解析陷阱与时区混乱。它直接来自 DateTime.ts,内部实现见 internal/dateTime.ts。
为什么 new Date 总是踩坑?
使用原生Date时,你大概率遇到过这些问题:
| 坑 | 表现 |
|---|---|
| 🔥 解析不一致 | new Date("2024-06-15")在 UTC 与本地时区下行为不同,甚至不同浏览器结果都不一样 |
| 🕐 时区混乱 | 同一"时刻"在不同时区显示不同钟面时间,转换全靠手算 |
| 🧪 无法测试 | 测试里时间不可控,涉及"今天/明天"的逻辑时断时断 |
| 🧟 可变对象 | setHours等方法原地修改,数据悄悄被改掉 |
effect-smol DateTime 模块的 5 个核心能力
DateTime用一个"绝对时刻(epoch 毫秒)+ 可选时区"的模型统一了这些问题:
- 安全解析:
DateTime.make接受字符串、时间戳、Date等多种输入,解析失败返回Option而不是静默产出错误值; - 可测试的当前时间:
DateTime.now走 Effect 的Clock服务,测试时可用 TestClock 精确控制"现在"是几点; - 时区感知:基于 IANA 时区(如
Pacific/Auckland)做钟面显示与转换,并支持CurrentTimeZone服务注入"当前用户时区"; - 不可变日历运算:
add/subtract/startOf/endOf/nearest等运算总是返回新值,原值永不被修改; - 稳定格式化:
formatIso、formatLocal、formatUtc等一组格式化函数,输出稳定、可控。
相关 API 全部定义在 DateTime.ts 中,测试用例可参考 DateTime.test.ts。
快速上手:从"获取当前时间"到"跨时区显示"
官方示例文档 10_creating-and-formatting.ts 展示了典型用法,核心只有几行:
const now = yield* DateTime.now // 可测试的当前时间 const endsAt = now.pipe(DateTime.add({ hours: 2 })) // 不可变运算 DateTime.formatIso(endsAt) // 稳定的 ISO 输出时区部分见 20_time-zones.ts:
const nowInAuckland = now.pipe(DateTime.setZoneNamedUnsafe("Pacific/Auckland")) const nowInNewYork = yield* DateTime.nowInCurrentZone // 由 CurrentTimeZone 服务提供💡 项目内部约定:Effect 程序里请用
DateTime模块,不要直接使用Date和Date.now(),详见 07_datetime/index.md。
新旧用法对照:迁移只需换几个 API
| 原生写法 | effect-smol DateTime 写法 | 好处 |
|---|---|---|
new Date(str) | DateTime.make(str) | 失败时显式得到None,不再静默出错 |
Date.now() | yield* DateTime.now | 测试中可冻结/拨动时间 |
new Date(t + 2 * 3600_000) | t.pipe(DateTime.add({ hours: 2 })) | 不可变、语义清晰 |
toLocaleString(...) | formatLocal/formatUtc | 输出稳定,时区明确 |
| 手算 UTC 偏移 | setZoneNamed+ IANA 时区 | 自动处理夏令时与历史变更 |
文件导航
- 核心模块:DateTime.ts
- 内部实现:internal/dateTime.ts
- 测试时间服务:testing/TestClock.ts
- 使用教程:ai-docs/src/07_datetime/
- 模块测试:test/DateTime.test.ts
总结
如果你受够了new Date的解析玄学、时区陷阱和不可测试性,effect-smol 的DateTime模块给出了工程化答案:安全解析 + 可测试时钟 + IANA 时区 + 不可变运算。迁移成本很低——把new Date换成DateTime.make,把Date.now()换成DateTime.now,剩下的坑就基本与你无关了 ✅
【免费下载链接】effect-smolCore libraries and experimental work for Effect v4项目地址: https://gitcode.com/GitHub_Trending/ef/effect-smol
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考