To format dates cleanly in JavaScript, prefer Day.js (or Intl.DateTimeFormat / date-fns) for new code because Moment.js is in maintenance mode, mutates dates by default, and adds substantial bundle weight, whereas Day.js is immutable, lightweight (~2 KB gzipped), and mirrors Moment-style token formatting ("YYYY-MM-DD", "MMM D, YYYY"). Always pass an explicit time zone or UTC mode (dayjs.utc(...) or timeZone in Intl.DateTimeFormat) when formatting timestamps across servers and clients so local machine offsets do not shift dates unexpectedly.
1. Formatting Dates with Day.js (Recommended Modern Alternative)
Install dayjs (and plugins like utc or timezone when needed) and format dates immutably using format tokens or locale-aware strings:
// Formatting dates cleanly with Day.js (immutable, token-based, and lightweight)
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc.js";
import timezone from "dayjs/plugin/timezone.js";
dayjs.extend(utc);
dayjs.extend(timezone);
function formatTimestamp(input, pattern = "YYYY-MM-DD HH:mm", tz = "Asia/Karachi") {
if (input === null || input === undefined) {
throw new TypeError("Expected a valid date input.");
}
const parsed = dayjs(input);
if (!parsed.isValid()) {
throw new RangeError(`Invalid date input: ${String(input)}`);
}
return parsed.tz(tz).format(pattern);
}
// Example usage:
console.log(formatTimestamp("2026-11-29T13:50:00Z", "MMM D, YYYY [at] h:mm A", "Asia/Karachi"));
// "Nov 29, 2026 at 6:50 PM"
console.log(dayjs.utc("2026-11-29T13:50:00Z").format("YYYY-MM-DD"));
// "2026-11-29"
- Validate with
.isValid(): Invalid date strings return"Invalid Date"in many libraries unless checked explicitly. - Escape literal text with square brackets: In Day.js and Moment.js format strings,
[at]outputs literalatrather than treatingaas meridiem.
2. Formatting with Moment.js (Legacy / Existing Codebases)
If an existing codebase already standardizes on Moment.js, guard input validity with moment(input).isValid(), use moment.utc(...) or .utcOffset() to avoid local time zone drift, and prefer explicit format tokens over ambiguous locale shortcuts:
// Formatting dates in an existing Moment.js codebase
import moment from "moment";
function formatWithMoment(input, formatToken = "YYYY-MM-DD", useUtc = true) {
if (input === null || input === undefined) {
throw new TypeError("Expected a valid date input.");
}
const instance = useUtc ? moment.utc(input) : moment(input);
if (!instance.isValid()) {
throw new RangeError(`Invalid date input: ${String(input)}`);
}
return instance.format(formatToken);
}
// Example usage:
console.log(formatWithMoment("2026-11-29T18:50:00+05:00", "ddd, DD MMM YYYY", true));
// "Sun, 29 Nov 2026"
- Watch out for mutability in Moment.js: Methods like
.add(),.startOf(), and.utc()mutate the Moment instance in place unless cloned first. - Avoid Moment for new greenfield projects: Its maintainers recommend modern immutable libraries or native date APIs for new applications.
3. Zero-Dependency Formatting with Intl.DateTimeFormat and Common Gotchas
When you need locale-aware display formatting (month names, weekday names, 12/24-hour clocks, and IANA time zones) with zero bundle overhead, use the built-in Intl.DateTimeFormat API:
// Built-in locale and time-zone aware formatting without external dependencies
function formatDisplayDate(dateInput, locale = "en-US", timeZone = "UTC") {
const date = dateInput instanceof Date ? dateInput : new Date(dateInput);
if (Number.isNaN(date.getTime())) {
throw new RangeError(`Invalid date input: ${String(dateInput)}`);
}
return new Intl.DateTimeFormat(locale, {
timeZone,
year: "numeric",
month: "short",
day: "2-digit",
hour: "2-digit",
minute: "2-digit"
}).format(date);
}
// Example usage:
console.log(formatDisplayDate("2026-11-29T13:50:00Z", "en-GB", "Asia/Karachi"));
// "29 Nov 2026, 18:50"
- Beware
"YYYY-MM-DD"vs"MM/DD/YYYY"parsing:new Date("2026-11-29")is parsed as UTC midnight, whereas slash formats like"11/29/2026"are parsed in local time and vary across environments. - Use ISO-8601 strings (
YYYY-MM-DDTHH:mm:ssZ) for data exchange: Format human-friendly strings at the UI/presentation layer while storing and transmitting unambiguous ISO timestamps.