isSame
Compares two dates and returns whether they share the same year, month, and day.
1/**
2 * Compares two dates and returns whether they share the same year, month, and day.
3 *
4 * @param date1 - The first date.
5 * @param date2 - The second date.
6 * @returns An object with flags for year, month, and day equality.
7 */
8export function isSame(
9 date1: Date,
10 date2: Date
11): { isSameYear: boolean; isSameMonth: boolean; isSameDay: boolean } {
12 const isSameYear = date1.getFullYear() === date2.getFullYear();
13 const isSameMonth = isSameYear && date1.getMonth() === date2.getMonth();
14 const isSameDay = isSameMonth && date1.getDate() === date2.getDate();
15
16 return { isSameYear, isSameMonth, isSameDay };
17}
Granular Comparison
Separately checks year, month, and day, giving fine-grained control over date similarity.
Efficient and Lightweight
Uses direct
Date
methods without complex logic or external libraries.Safe Hierarchical Evaluation
Short-circuits comparisons - month is only compared if the year matches, and day only if month matches - preventing unnecessary computation.
Useful Structured Output
Returns an object with named flags instead of a boolean, enabling more expressive usage and readability.
Tests | Examples
1test('isSame - full match (same day)', () => {
2 const a = new Date('2024-06-27');
3 const b = new Date('2024-06-27');
4 expect(isSame(a, b)).toEqual({
5 isSameYear: true,
6 isSameMonth: true,
7 isSameDay: true,
8 });
9});
10
11test('isSame - same year and month, different day', () => {
12 const a = new Date('2024-06-27');
13 const b = new Date('2024-06-25');
14 expect(isSame(a, b)).toEqual({
15 isSameYear: true,
16 isSameMonth: true,
17 isSameDay: false,
18 });
19});
20
21test('isSame - same year, different month', () => {
22 const a = new Date('2024-06-27');
23 const b = new Date('2024-05-27');
24 expect(isSame(a, b)).toEqual({
25 isSameYear: true,
26 isSameMonth: false,
27 isSameDay: false,
28 });
29});
30
31test('isSame - completely different', () => {
32 const a = new Date('2024-06-27');
33 const b = new Date('2023-05-15');
34 expect(isSame(a, b)).toEqual({
35 isSameYear: false,
36 isSameMonth: false,
37 isSameDay: false,
38 });
39});
Common Use Cases
UI Highlighting
Highlight calendar elements when two dates fall on the same day/month/year.
Log Grouping
Cluster events or records that occur on the same day, month, or year.
Change Detection
Detect when the user has selected a new day, month, or year compared to the previous value.
Validation Checks
Ensure user input matches a reference date in specific parts (e.g., year only or month and day).
Versioning or Snapshot Logic
Compare timestamped entries to detect if changes occurred on the same calendar day.