How do you check whether a JavaScript Date object is "Invalid Date"? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you check whether a JavaScript Date object is ""Invalid Date""?

message-square
0

To check whether a JavaScript Date instance represents an "Invalid Date", first verify value instanceof Date and then check Number.isNaN(value.getTime()) (or Number.isNaN(value.valueOf())). Under the ECMAScript specification, any invalid Date object has an underlying time value of NaN, while its string representation (.toString() / .toDateString()) returns "Invalid Date". Checking Number.isNaN(date.getTime()) is fast, unambiguous, and does not mutate the Date instance.


1. Checking "Invalid Date" with instanceof Date and Number.isNaN(d.getTime())

Validate that the input is an actual Date instance first, check d.getTime() with Number.isNaN(), and return a boolean without mutating the Date object:

// Return true if value is a Date instance whose internal timestamp is NaN ("Invalid Date")
function isInvalidDate(value) {
  if (!(value instanceof Date)) {
    throw new TypeError("Expected value to be an instance of Date.");
  }

  return Number.isNaN(value.getTime());
}

// Safe helper that returns boolean validity for any arbitrary value (no throw on non-Date)
function isValidDateInstance(value) {
  return value instanceof Date && !Number.isNaN(value.getTime());
}

// Example usage:
const badDate = new Date("not-a-real-date");
const goodDate = new Date("2026-11-28T11:57:00+05:00");

console.log("Is badDate Invalid Date?", isInvalidDate(badDate)); // true
console.log("Is goodDate valid?", isValidDateInstance(goodDate)); // true
console.log("Is plain string valid Date?", isValidDateInstance("2026-11-28")); // false
  • Specification-backed check: An invalid Date always yields NaN from .getTime(), and Number.isNaN() avoids unintended type coercion.
  • Non-mutating: Inspects .getTime() read-only without modifying value.

2. Normalizing or Guarding Date Inputs Before Formatting or Sorting

Before calling .toISOString() or .getTime() on user or API date inputs, guard against non-Date values and "Invalid Date" instances so formatting code does not throw RangeError: Invalid time value:

// Format a valid Date to ISO string or return a safe fallback when invalid/non-Date
function toSafeIsoString(candidate, fallback = null) {
  if (!isValidDateInstance(candidate)) {
    return fallback;
  }

  const ms = candidate.getTime();
  if (!Number.isFinite(ms)) {
    return fallback;
  }

  return candidate.toISOString();
}

// Example usage:
console.log(toSafeIsoString(new Date("invalid"), "N/A")); // "N/A"
console.log(toSafeIsoString(new Date("2026-11-28T06:57:00.000Z"), "N/A")); // "2026-11-28T06:57:00.000Z"
  • Prevents RangeError in .toISOString(): Calling .toISOString() on an "Invalid Date" throws RangeError: Invalid time value.
  • Clean fallback behavior: Returns a predictable fallback instead of propagating broken timestamps downstream.

3. Common Traps to Avoid

Checking whether a JavaScript Date is "Invalid Date" often runs into a few pitfalls:

  • Testing date === NaN or date == "Invalid Date": An invalid Date is still an object (typeof d === "object"), not the primitive NaN, and d == "Invalid Date" is false (though String(d) === "Invalid Date" is true).
  • Using global isNaN(d.getTime()) vs Number.isNaN(d.getTime()): While d.getTime() returns a number or NaN, Number.isNaN() is preferred because it never coerces non-numeric arguments unexpectedly.
  • Assuming typeof d === "object" means d instanceof Date: Plain objects, null, and new Date("x") all have typeof === "object"—always verify instanceof Date when expecting a Date instance.

TL;DR: Check value instanceof Date && Number.isNaN(value.getTime()) to detect an "Invalid Date" instance safely without mutating the object or triggering RangeError in .toISOString().