Skip to content

ensureDate

Safely converts a date-like value to a valid Date object, or returns null.

Accepts Date, timestamps (seconds or milliseconds, auto-detected), date strings, and objects with an epochMilliseconds property (e.g. Temporal.Instant, Temporal.ZonedDateTime). Returns null for null, undefined, empty strings, 0, and any value that produces an invalid Date.

This is the date equivalent of ensureArray — it normalizes flexible input into a guaranteed type (or a safe fallback).

Available since v2.0.0

import { ensureDate } from '@helpers4/date';
// or, from the all-in-one package (same code, one install):
import { ensureDate } from 'helpers4/date';
ensureDate(input: DateLike | null | undefined): Date | null
ParameterTypeDescription
inputDateLike | null | undefinedA date-like value to convert

Date | null — A valid Date object, or null if the input is invalid

ensureDate('2025-01-19T12:00:00Z') // => Date
ensureDate(1737290400)             // => Date (from Unix seconds)
ensureDate(1737290400000)          // => Date (from milliseconds)
ensureDate(new Date())             // => Date (same reference)
ensureDate(null)                   // => null
ensureDate('invalid')              // => null

A value that can be converted to a Date.

  • Date — used as-is (validated for Invalid Date)
  • number — treated as a timestamp (seconds or milliseconds, auto-detected); 0 is treated as invalid and produces null in ensureDate
  • string — parsed via new Date(string)
  • Temporal.Instant | Temporal.ZonedDateTime — read via their epochMilliseconds property
type DateLike = Date | number | string | Temporal.Instant | Temporal.ZonedDateTime

View source on GitHub