The getTime function returns the timestamp (milliseconds since Unix epoch) of the given date. It validates the input before processing and provides a safe way to extract timestamps from Date objects or numeric timestamps.
function getTime(date: DateInput): number;
| Parameter | Type | Description |
|---|---|---|
date |
DateInput |
A Date object, numeric timestamp, or ISO 8601 string to convert to a timestamp |
| Type | Description |
|---|---|
number |
The timestamp in milliseconds since Unix epoch (1970-01-01T00:00:00.000Z), or NaN if the input is invalid |
The getTime function extracts the timestamp value from a Date object or validates and returns a numeric timestamp as-is. It ensures consistent validation across the Chronia library by checking input validity before processing.
Date object (not Invalid Date)0, representing January 1, 1970, 00:00:00 UTC)NaN when:new Date('invalid'))NaNInfinity-InfinityisValidDateOrNumber validator for consistencygetTime() method after validationNaNDate | numberNaN for invalid inputs to enable graceful error handling.import { getTime } from "chronia";
// Extract timestamp from Date object
const timestamp = getTime(new Date("2024-01-01T00:00:00.000Z"));
// Returns: 1704067200000
// Unix epoch (zero timestamp)
const epoch = getTime(new Date(0));
// Returns: 0
// Negative timestamp (before Unix epoch)
const beforeEpoch = getTime(new Date("1969-12-31T00:00:00.000Z"));
// Returns: -86400000
// Invalid date returns NaN
const invalid = getTime(new Date("invalid"));
// Returns: NaN
import { getTime } from "chronia";
// Calculate time difference between two dates
function getDifferenceInMilliseconds(date1: Date, date2: Date): number {
const time1 = getTime(date1);
const time2 = getTime(date2);
// Check for invalid inputs
if (isNaN(time1) || isNaN(time2)) {
return NaN;
}
return Math.abs(time1 - time2);
}
const diff = getDifferenceInMilliseconds(
new Date("2024-01-02"),
new Date("2024-01-01"),
);
// Returns: 86400000 (24 hours in milliseconds)
import { getTime } from "chronia";
// Handle mixed input types
function normalizeToTimestamp(date: Date | number): number {
return getTime(date);
}
// Date object input
normalizeToTimestamp(new Date("2024-01-01"));
// Returns: 1704067200000
// Numeric timestamp input (validated and returned as-is)
normalizeToTimestamp(1704067200000);
// Returns: 1704067200000
// Invalid input
normalizeToTimestamp(NaN);
// Returns: NaN
import { getTime } from "chronia";
// Safe timestamp conversion with validation
function formatTimestamp(date: Date | number): string {
const timestamp = getTime(date);
if (isNaN(timestamp)) {
return "Invalid timestamp";
}
return `Timestamp: ${timestamp}`;
}
// Valid input
formatTimestamp(new Date("2024-01-01"));
// Returns: "Timestamp: 1704067200000"
// Invalid input
formatTimestamp(new Date("invalid"));
// Returns: "Invalid timestamp"