JavaScript Date Formatting with date-fns, moment, and dayjs
Master JavaScript date formatting using date-fns, moment.js, and Day.js libraries. Compare token syntax, learn Intl.DateTimeFormat, and see practical code examples.
Detailed Explanation
JavaScript Date Formatting
JavaScript's native Date object has limited formatting options. Most developers use a library for custom format strings. The three most popular libraries — date-fns, moment.js, and Day.js — share very similar token syntax.
Native JavaScript Options
const d = new Date();
d.toISOString(); // "2026-02-28T05:30:00.000Z"
d.toLocaleDateString(); // Locale-dependent
d.toLocaleString("en-US"); // "2/28/2026, 2:30:00 PM"
The Intl.DateTimeFormat API provides locale-aware formatting:
new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "long",
day: "numeric",
}).format(d); // "February 28, 2026"
date-fns / Day.js / moment Token Syntax
These libraries use a common pattern syntax:
| Token | Output | Description |
|---|---|---|
yyyy |
2026 | Full year |
yy |
26 | Two-digit year |
MM |
02 | Month (zero-padded) |
MMM |
Feb | Abbreviated month |
MMMM |
February | Full month name |
dd |
28 | Day (zero-padded) |
HH |
14 | Hour 24h (zero-padded) |
hh |
02 | Hour 12h (zero-padded) |
mm |
30 | Minutes |
ss |
00 | Seconds |
a |
PM | AM/PM |
Library Comparison
// date-fns
import { format } from "date-fns";
format(new Date(), "yyyy-MM-dd HH:mm:ss");
// Day.js
import dayjs from "dayjs";
dayjs().format("YYYY-MM-DD HH:mm:ss");
// moment.js (legacy)
import moment from "moment";
moment().format("YYYY-MM-DD HH:mm:ss");
Note: moment.js uses uppercase YYYY and DD, while date-fns uses lowercase yyyy and dd. Day.js follows moment's conventions.
Timezone Handling
For timezone-aware formatting, use date-fns-tz, dayjs/plugin/timezone, or the native Intl.DateTimeFormat with timeZone option.
Use Case
JavaScript date formatting is needed in every web application: displaying dates in user profiles, formatting timestamps in chat messages, generating date-based file names, creating human-readable log entries, and building date picker components. Choosing between date-fns (tree-shakable), Day.js (tiny), and moment.js (legacy) depends on bundle size requirements.