The first Date object or timestamp to compare
The second Date object or timestamp to compare
Comparison options with default { order: "ASC" }
-1 if date1 < date2, 1 if date1 > date2, 0 if equal (adjusted for order) Returns NaN if inputs are invalid
// Compare Date objects with default ascending order
compare(new Date('2024-01-01'), new Date('2024-01-02')); // -1 (ascending)
compare(new Date('2024-01-01'), new Date('2024-01-01')); // 0 (equal)
// Compare with explicit descending order
compare(new Date('2024-01-01'), new Date('2024-01-02'), { order: 'DESC' }); // 1 (descending)
// Compare timestamps
const timestamp1 = new Date('2024-01-01').getTime();
const timestamp2 = new Date('2024-01-02').getTime();
compare(timestamp1, timestamp2); // -1 (ascending)
compare(timestamp1, timestamp2, { order: 'DESC' }); // 1 (descending)
// Compare mixed Date and timestamp inputs
compare(new Date('2024-01-01'), new Date('2024-01-02').getTime()); // -1
compare(timestamp1, new Date('2024-01-02')); // -1
// Empty options object defaults to ascending order
compare(date1, date2, {}); // Same as compare(date1, date2)
// Order property is case-insensitive at runtime
// These work at runtime even though TypeScript will show type errors:
// compare(date1, date2, { order: 'desc' }); // treated as 'DESC'
// compare(date1, date2, { order: 'asc' }); // treated as 'ASC'
// compare(date1, date2, { order: 'xyz' }); // treated as 'ASC' (default)
Compare two Date objects or timestamps chronologically with configurable sort order.