API reference › @evolu/common › Type › ValidDate

const ValidDate: brand(
  "ValidDate",
  Date,
  (value: globalThis.Date) =>
    globalThis.Number.isNaN(globalThis.Date.prototype.getTime.call(value))
      ? err<ValidDateError>({ type: "ValidDate", value })
      : ok(),
  formatValidDateError,
);

Defined in: packages/common/src/Type.ts:4071

A Date with a valid time value.

Rejects an Invalid Date, such as new Date("x"), whose time value is NaN. Like Date, it is realm-neutral: it reads the time value with Date.prototype.getTime instead of a method of the value.

A Date is mutable, so calling setTime(NaN) on a validated value breaks its brand. Use DateIsoFromDate to store a moment and Millis for time arithmetic.

Example

import {
  assertEqual,
  assertErr,
  assertOk,
  assertType,
  ValidDate,
  type Brand,
} from "@evolu/common";

const date = new Date(0);
assertOk(ValidDate.fromUnknown(date), date);
assertType<ValidDate, Date & Brand<"ValidDate">>();

const invalidDate = new Date("x");
const invalid = ValidDate.fromUnknown(invalidDate);
assertErr(invalid, { type: "ValidDate", value: invalidDate });
assertEqual(ValidDate.formatError(invalid.error), "The Date is invalid.");