• Not Exported

    Creates a valid Date object from various timestamp formats

    Safely handles timestamp conversion from multiple possible formats to a proper Date object, with robust error handling for invalid inputs. This function manages:

    • String timestamps (both ISO format and numeric strings)
    • Numeric timestamps (milliseconds since epoch)
    • Validation of resulting Date objects

    Parameters

    • timestamp: string | number

      Input timestamp in string or number format

    Returns null | Date

    Valid Date object or null if parsing fails

    // Create date from ISO string
    const date1 = createSafeDate("2023-01-15T14:30:00Z");

    // Create date from numeric timestamp
    const date2 = createSafeDate(1673793000000);
    function createSafeDate(timestamp: string | number): Date | null {
    try {
    // Check if timestamp is already a Date (though this shouldn't happen with our types)
    if (typeof timestamp === "object" && timestamp && "getTime" in timestamp) {
    return timestamp as Date;
    }

    // If timestamp is a string that looks like a number, convert it to a number
    if (typeof timestamp === "string" && /^\d+$/.test(timestamp)) {
    timestamp = parseInt(timestamp, 10);
    }

    // Create a Date object from the timestamp
    const date = new Date(timestamp);

    // Check if the date is valid
    if (isNaN(date.getTime())) {
    return null;
    }

    return date;
    } catch {
    return null;
    }
    }