Safely converts any timestamp format to a Date object

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 (ISO or numeric)

    Returns null | Date

    Date object or null if invalid