To compare two dates or timestamps in Moment.js, parse both inputs explicitly with moment(input, format, strict) (or validate existing moment / Date / numeric timestamp inputs), verify validity using moment.isMoment() and .isValid(), and compare them with .isBefore(), .isSame(), .isAfter() (passing a unit such as "day", "hour", or "millisecond" when granularity matters) or .diff() inside a try / catch block—storing comparison outcomes or unit results in a Map so dynamic keys never collide with Object.prototype properties.
1. Validating Inputs and Comparing Dates or Timestamps with isBefore(), isSame(), and isAfter()
Always check that Moment.js is available (typeof moment === "function"), normalize timestamps/strings/dates into valid Moment instances, and compare with an explicit unit ("millisecond", "second", "minute", "hour", "day") inside try / catch:
// Normalize a date/timestamp input and compare two Moment instances safely
function compareMomentDates(leftInput, rightInput, {
format = undefined,
strict = false,
granularity = "millisecond",
momentRef = (typeof moment !== "undefined" ? moment : null)
} = {}) {
if (typeof momentRef !== "function") {
throw new TypeError("Expected momentRef to be a valid Moment.js function.");
}
if (format !== undefined && (typeof format !== "string" || format.trim().length === 0)) {
throw new TypeError("Expected format to be undefined or a non-empty string.");
}
if (typeof strict !== "boolean") {
throw new TypeError("Expected strict to be a boolean.");
}
if (typeof granularity !== "string" || granularity.trim().length === 0) {
throw new TypeError("Expected granularity to be a non-empty string.");
}
const toValidMoment = (rawVal, label) => {
if (rawVal === null || rawVal === undefined) {
throw new TypeError(`Expected ${label} date/timestamp to be non-null and defined.`);
}
if (typeof rawVal !== "string" && typeof rawVal !== "number" && !(rawVal instanceof Date) && !momentRef.isMoment(rawVal)) {
throw new TypeError(`Expected ${label} to be a string, number timestamp, Date, or Moment instance.`);
}
if (typeof rawVal === "number" && (!Number.isFinite(rawVal))) {
throw new RangeError(`Expected numeric timestamp ${label} to be a finite number.`);
}
const mObj = momentRef.isMoment(rawVal)
? rawVal.clone()
: (format ? momentRef(rawVal, format, strict) : momentRef(rawVal));
if (!mObj.isValid()) {
throw new RangeError(`Invalid ${label} date/timestamp provided to Moment.js.`);
}
return mObj;
};
try {
const leftMoment = toValidMoment(leftInput, "left");
const rightMoment = toValidMoment(rightInput, "right");
const unit = granularity.trim();
const isBefore = leftMoment.isBefore(rightMoment, unit);
const isSame = leftMoment.isSame(rightMoment, unit);
const isAfter = leftMoment.isAfter(rightMoment, unit);
const diffMs = leftMoment.diff(rightMoment);
const diffInUnit = leftMoment.diff(rightMoment, unit);
return new Map([
["leftUnixMs", leftMoment.valueOf()],
["rightUnixMs", rightMoment.valueOf()],
["granularity", unit],
["isBefore", isBefore],
["isSame", isSame],
["isAfter", isAfter],
["diffMs", diffMs],
["diffInUnit", diffInUnit]
]);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed comparing dates/timestamps in Moment.js: ${message}`);
}
}
// Example usage:
// try {
// const cmpMap = compareMomentDates(1735689600000, "2025-01-02T00:00:00Z", {
// granularity: "day"
// });
// console.log("Left before right (by day):", cmpMap.get("isBefore"));
// console.log("Day difference:", cmpMap.get("diffInUnit"));
// } catch (error) {
// console.error(`${error.name}: ${error.message}`);
// }
- Always pass a granularity unit to
isSame(),isBefore(), orisAfter()when calendar/day/hour boundaries matter: Without a unit, comparison defaults to milliseconds ("millisecond"). - Use
.valueOf()for exact millisecond epoch timestamps: Returns Unix epoch milliseconds (number) for numeric sorting or storage.
2. Comparing Multi-Unit Differences and Time Windows with a Map
When calculating differences across multiple units (such as days, hours, and minutes) or checking multiple comparison predicates at once, store results in a Map inside try / catch so dynamic keys never collide with Object.prototype properties:
// Compute multi-unit differences between two Moment-compatible dates/timestamps into a Map
function getMomentDiffBreakdown(startInput, endInput, unitsList = ["days", "hours", "minutes", "seconds"], {
momentRef = (typeof moment !== "undefined" ? moment : null)
} = {}) {
if (typeof momentRef !== "function") {
throw new TypeError("Expected momentRef to be a valid Moment.js function.");
}
if (!Array.isArray(unitsList)) {
throw new TypeError("Expected unitsList to be an Array instance.");
}
try {
const startMoment = momentRef.isMoment(startInput) ? startInput.clone() : momentRef(startInput);
const endMoment = momentRef.isMoment(endInput) ? endInput.clone() : momentRef(endInput);
if (!startMoment.isValid() || !endMoment.isValid()) {
throw new RangeError("Both startInput and endInput must parse to valid Moment dates.");
}
const breakdownMap = new Map([
["startMs", startMoment.valueOf()],
["endMs", endMoment.valueOf()],
["endAfterStart", endMoment.isAfter(startMoment)]
]);
for (let i = 0; i < unitsList.length; i += 1) {
const unitName = unitsList[i];
if (typeof unitName !== "string" || unitName.trim().length === 0) {
throw new TypeError(`Expected unit at index ${i} to be a non-empty string.`);
}
const cleanUnit = unitName.trim();
breakdownMap.set(cleanUnit, endMoment.diff(startMoment, cleanUnit));
}
return breakdownMap;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed building Moment diff breakdown: ${message}`);
}
}
// Example usage:
// try {
// const diffMap = getMomentDiffBreakdown("2026-11-29T09:00:00Z", "2026-11-29T21:30:00Z", ["hours", "minutes"]);
// console.log("Hours elapsed:", diffMap.get("hours"), "Minutes elapsed:", diffMap.get("minutes"));
// } catch (error) {
// console.error(`${error.name}: ${error.message}`);
// }
- Use
Mapfor unit difference keys: AvoidsObject.prototypecollisions (constructor,toString,hasOwnProperty) when unit names are dynamic. - Note
.diff()truncation toward zero by default: Passtrueas the third argument to.diff(other, unit, true)only when floating-point fractional units are intentionally needed.
3. Unix Seconds vs. Milliseconds, Timezones, and Moment Caveats
Keep these date and timestamp comparison caveats in mind in production code:
- Seconds vs. milliseconds timestamps: Numeric timestamps in JavaScript and
moment(ms)expect milliseconds; for 10-digit Unix seconds, convert withmoment.unix(seconds)rather than passing seconds directly as milliseconds. - Timezones and DST shifts affect calendar units (
"day","month"): Comparing two dates in different timezones or across Daylight Saving Time transitions can shift calendar day boundaries—normalize timezones consistently (e.g., UTC via.utc()) when comparing across regions. - Moment.js is in maintenance mode for new projects: Keep existing Moment.js wrappers defensive and consistent in legacy codebases, while considering modern alternatives (
Intl.DateTimeFormat, Temporal API, or lightweight date libraries) for new greenfield code.
