Safely parses different timestamp formats into a standardized Date object

Handles multiple timestamp formats that may exist in the dataset:

  • ISO 8601 date strings
  • Unix timestamp milliseconds as strings
  • Other date string formats

Returns null for invalid or empty timestamps to enable safe optional chaining.

export const parseTimestamp = (timestamp: string): Date | null => {
if (!timestamp) return null;

try {
if (!isNaN(Number(timestamp))) {
return new Date(Number(timestamp));
} else {
return new Date(timestamp);
}
} catch (error) {
console.error("Error parsing timestamp:", error);
return null;
}
};
  • Parameters

    • timestamp: string

      Timestamp string in any supported format

    Returns null | Date

    Standardized Date object or null if invalid