What date-fns Does
- Format — 50+ format tokens, locale-aware
- Parse — strict parsing, ISO, custom formats
- Arithmetic — add/sub days, months, years, hours, minutes, weeks
- Comparison — isAfter, isBefore, isEqual, closestTo
- Difference — differenceInDays/Hours/Minutes
- Distance — formatDistance, formatDistanceToNow (relative strings)
- Locales — 70+ locales
- Timezone — via date-fns-tz adapter
- Immutable — every function returns a new Date
Architecture
Pure functions over native Date objects — no classes, no wrappers. Each function is a separate module. Locales are separate imports for tree-shakeability. Types are native TypeScript (not @types).
Self-Hosting
Client or server library, zero runtime deps.
Key Features
- 200+ pure functions
- Tree-shakeable (v2+)
- TypeScript native
- 70+ locales
- Immutable
- Small (~15KB with common functions)
- No Moment-style mutable object
- ESM and CJS builds
- Native Date compatible
Comparison
| Library | Size | API Style | Tree-shake | Timezone |
|---|---|---|---|---|
| date-fns | ~15KB used | Functional | Yes | Via plugin |
| Day.js | ~6KB | Chainable (Moment-like) | Plugins | Via plugin |
| Luxon | ~30KB | OO (classes) | No | Built-in |
| Moment | ~230KB | Mutable classes | No | Built-in |
| Temporal (TC39) | Native | Modern API | N/A | Native |
常见问题 FAQ
Q: 和 Day.js 选哪个? A: date-fns 更纯函数、tree-shaking 更好;Day.js 更像 Moment、链式 API 更顺手。看个人偏好。
Q: Timezone 怎么处理?
A: 用 date-fns-tz 补充包,提供 zonedTimeToUtc、formatInTimeZone 等。
Q: 等 Temporal 出了就不需要了? A: Temporal 还未全面落地(Safari 部分支持),polyfill 方案 ~60KB。短期内 date-fns 仍是主流。
来源与致谢 Sources
- Docs: https://date-fns.org
- GitHub: https://github.com/date-fns/date-fns
- License: MIT