Course contentsShow
← Web Development
Lesson 2739 of 2,98249. Dates, Times, and Numbers on the WebFree lesson

date-fns: Comparison and Validation

Comparing dates with isBefore, isAfter, isEqual, and validating ranges with isWithinInterval.

date-fns: Comparison and Validation

What you'll learn: How to safely compare dates and validate date ranges using date-fns helper functions that eliminate ambiguity and edge cases.

Why Comparison Matters

With native Date objects, comparing dates can be tricky. You might compare timestamps directly, but this fails for questions like "is this date before that one, ignoring time?" or "does this fall within a range?" The date-fns library provides dedicated functions that make comparisons explicit and readable.

Comparison Functions

Think of these as asking clear yes/no questions about dates:

isBefore(dateA, dateB) – Returns true if dateA comes chronologically before dateB.

isAfter(dateA, dateB) – Returns true if dateA comes chronologically after dateB.

isEqual(dateA, dateB) – Returns true if both dates represent the exact same millisecond in time. Unlike ===, this correctly compares different Date instances with identical values.

These functions handle different date formats (Date objects, ISO strings, timestamps) and always return clear boolean results.

Range Validation

isWithinInterval(date, { start, end }) – Checks if a date falls within a specified interval, inclusive of boundaries.

This is like asking "is this appointment during business hours?" You define the interval with start and end properties, and the function handles all edge cases, including boundary inclusivity.

Real-World Application

These functions replace fragile manual comparisons. Instead of new Date(a) > new Date(b), you write isAfter(a, b), making intent crystal clear. For validating bookings, event eligibility, or access windows, isWithinInterval removes the mental overhead of boundary logic.

Key Takeaway: Use isBefore, isAfter, isEqual for clear date comparisons, and isWithinInterval for robust range validation—these functions make temporal logic readable and correct.