isValidDate
Checks if a given value is a valid Date object.
1/**
2 * Checks if a given value is a valid Date object.
3 *
4 * @param value - The value to check.
5 * @returns True if the value is a valid Date, false otherwise.
6 */
7export function isValidDate(value: any): boolean {
8 return value instanceof Date && !isNaN(value.getTime());
9}
Accurate Validation
Combines
instanceof Date
with!isNaN(getTime())
to ensure the value is both a Date object and holds a valid timestamp.Prevents Naive Type Checks
Avoids false positives that might occur from just checking the object type, catching
Invalid Date
cases reliably.Lightweight and Efficient
Performs minimal operations for validation, making it suitable for performance-sensitive code.
Safe Type Guard
Can act as a type guard in TypeScript, improving safety when working with dynamic input values.
Tests | Examples
1test('returns true for valid Date objects', () => {
2 expect(isValidDate(new Date())).toBe(true);
3 expect(isValidDate(new Date('2023-01-01'))).toBe(true);
4});
5
6test('returns false for invalid Date objects', () => {
7 expect(isValidDate(new Date('invalid date'))).toBe(false);
8});
9
10test('returns false for non-Date types', () => {
11 expect(isValidDate(Date.now())).toBe(false);
12 expect(isValidDate('2023-01-01')).toBe(false);
13 expect(isValidDate(null)).toBe(false);
14 expect(isValidDate(undefined)).toBe(false);
15 expect(isValidDate({})).toBe(false);
16});
Common Use Cases
Parsing User Input
Validate date values entered via forms or APIs to ensure they're not invalid or malformed.
Sanity Checks in Date Calculations
Prevent runtime errors by confirming inputs are valid dates before doing arithmetic or formatting.
Data Validation in ETL Pipelines
Clean or filter out invalid date entries when processing datasets.
Form Validation and Feedback
Provide user feedback if a selected or typed date is not recognized as valid.
Preventing Logic Errors in Time-Based Logic
Ensure that only valid date objects are used in comparisons, sorting, and scheduling functions.