isInRange
Checks if a date is within a given range (inclusive).
1/**
2 * Checks if a date is within a given range (inclusive).
3 *
4 * @param date - The date to check.
5 * @param start - Start of the range.
6 * @param end - End of the range.
7 * @returns True if the date is between start and end, inclusive.
8 */
9export function isInRange(date: Date, start: Date, end: Date): boolean {
10 const time = date.getTime();
11
12 return time >= start.getTime() && time <= end.getTime();
13}
Inclusive Comparison Logic
Includes both start and end boundaries, making it suitable for most real-world scenarios where edge values are valid.
Straightforward Implementation
Uses direct timestamp comparison for efficient and clear logic.
Pure and Deterministic
Stateless design ensures consistent behavior with no side effects or dependencies.
Reusable Across Contexts
Applicable to a wide range of time-based validations, not tied to any specific domain or data structure.
Tests | Examples
1test('isInRange - returns true for a date inside the range', () => {
2 const start = new Date('2024-01-01');
3 const end = new Date('2024-12-31');
4 const date = new Date('2024-06-15');
5 expect(isInRange(date, start, end)).toBe(true);
6});
7
8test('isInRange - returns true for start boundary', () => {
9 const start = new Date('2024-01-01');
10 const end = new Date('2024-12-31');
11 expect(isInRange(start, start, end)).toBe(true);
12});
13
14test('isInRange - returns true for end boundary', () => {
15 const start = new Date('2024-01-01');
16 const end = new Date('2024-12-31');
17 expect(isInRange(end, start, end)).toBe(true);
18});
19
20test('isInRange - returns false for date before range', () => {
21 const start = new Date('2024-01-01');
22 const end = new Date('2024-12-31');
23 const date = new Date('2023-12-31');
24 expect(isInRange(date, start, end)).toBe(false);
25});
26
27test('isInRange - returns false for date after range', () => {
28 const start = new Date('2024-01-01');
29 const end = new Date('2024-12-31');
30 const date = new Date('2025-01-01');
31 expect(isInRange(date, start, end)).toBe(false);
32});
Common Use Cases
Date Range Validation
Ensure a user-selected date (e.g. booking or submission) falls within a permitted range.
Access Control Windows
Check if the current time is within an allowed timeframe for actions like login or voting.
Analytics Filtering
Determine if a timestamped event falls within a reporting or aggregation period.
UI Highlighting
Visually emphasize days or periods that fall within a selected or preset date range.
Promotion or Campaign Checks
Validate whether a date is within a limited-time offer or marketing window.