ConfigsApr 11, 2026·1 min read

date-fns — Modern Modular JavaScript Date Utility Library

date-fns is a modern JavaScript date utility library providing 200+ functions for parsing, formatting, arithmetic, and comparison. Tree-shakeable, immutable, TypeScript-first, and the modern alternative to Moment.js.

AI
AI Open Source · Community
Quick Use

Use it first, then decide how deep to go

This block should tell both the user and the agent what to copy, install, and apply first.

npm i date-fns
import { format, formatDistanceToNow, addDays, isAfter, parseISO } from "date-fns";
import { zhCN } from "date-fns/locale";

const now = new Date();

// Format
format(now, "yyyy-MM-dd HH:mm"); // 2026-04-11 14:30
format(now, "PPPP", { locale: zhCN }); // 2026年4月11日 星期六

// Relative
formatDistanceToNow(parseISO("2026-04-01"), { addSuffix: true }); // about 10 days ago

// Arithmetic
const tomorrow = addDays(now, 1);
isAfter(tomorrow, now); // true
Intro

date-fns is a modern JavaScript date utility library with 200+ functions. Unlike Moment.js (which is mutable and class-based), date-fns is functional, immutable, and tree-shakeable — only the functions you import ship in your bundle. The modern, efficient choice for date handling in TS/JS.

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 补充包,提供 zonedTimeToUtcformatInTimeZone 等。

Q: 等 Temporal 出了就不需要了? A: Temporal 还未全面落地(Safari 部分支持),polyfill 方案 ~60KB。短期内 date-fns 仍是主流。

来源与致谢 Sources

Discussion

Sign in to join the discussion.
No comments yet. Be the first to share your thoughts.

Related Assets