The isValid function validates whether a given Date object or timestamp represents a valid date. It provides a reliable way to check date validity in Chronia’s consistent API surface.
function isValid(date: DateInput): boolean;
| Parameter | Type | Description |
|---|---|---|
date |
DateInput |
A Date object, numeric timestamp, or ISO 8601 string to validate |
| Type | Description |
|---|---|
boolean |
Returns true if the date is valid, false otherwise |
The isValid function determines whether the provided Date object or timestamp represents a valid date/time value. It leverages Chronia’s internal validation utilities to ensure consistency across the library.
true when:Date object (not Invalid Date)0, representing January 1, 1970, 00:00:00 UTC)false when:new Date('invalid'))NaNInfinity-InfinityfalseDate | numberimport { isValid, parse } from "chronia";
// Validate parsed date
function processUserDate(input: string): Date | null {
const parsed = parse(input, "yyyy-MM-dd");
return isValid(parsed) ? parsed : null;
}
// Valid Date object
isValid(new Date(2025, 0, 1)); // Returns: true
// Valid timestamp
isValid(Date.now()); // Returns: true
// Zero timestamp (Unix epoch)
isValid(0); // Returns: true
// Negative timestamp (before Unix epoch)
isValid(-1000); // Returns: true
// Invalid Date object
isValid(new Date("invalid")); // Returns: false
// Invalid numeric values
isValid(NaN); // Returns: false
isValid(Infinity); // Returns: false
isValid(-Infinity); // Returns: false
import { isValid, format } from "chronia";
function formatDate(date: Date | number): string {
if (!isValid(date)) {
return "Invalid date";
}
return format(date, "yyyy-MM-dd");
}
// Safe date formatting
formatDate(new Date(2025, 0, 1)); // Returns: '2025-01-01'
formatDate(new Date("invalid")); // Returns: 'Invalid date'
import { isValid } from "chronia";
const dates = [new Date(2025, 0, 1), new Date("invalid"), Date.now(), NaN];
const validDates = dates.filter(isValid);
// Returns: [new Date(2025, 0, 1), Date.now()]
import { isValid, parse, format } from "chronia";
function parseAndFormat(dateString: string): string {
const parsed = parse(dateString, "yyyy-MM-dd");
if (!isValid(parsed)) {
return "Failed to parse date. Please use yyyy-MM-dd format.";
}
return format(parsed, "MMMM d, yyyy");
}
parseAndFormat("2025-01-01"); // Returns: 'January 1, 2025'
parseAndFormat("invalid"); // Returns: 'Failed to parse date. Please use yyyy-MM-dd format.'