Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

daysBetween

Returns the number of full days between two dates.

TypeScript
Copied!
1/**
2 * Returns the number of full days between two dates.
3 *
4 * @param date1 - The first date.
5 * @param date2 - The second date.
6 * @returns Number of days between the two dates (absolute value).
7 */
8export function daysBetween(date1: Date, date2: Date): number {
9  const msPerDay = 1000 * 60 * 60 * 24;
10  const utc1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
11  const utc2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());
12
13  return Math.abs(Math.floor((utc2 - utc1) / msPerDay));
14}
  • Timezone-Independent Calculation

    Uses Date.UTC to avoid local timezone shifts and daylight saving issues when comparing dates.

  • Returns Whole Days Only

    Rounds down to the nearest full day, which is typically more relevant for calendrical comparisons.

  • Handles Date Order Gracefully

    Always returns a non-negative number, regardless of the order of inputs.

  • Pure and Side-Effect Free

    Operates without mutating inputs and always returns a predictable, numeric result.

Tests | Examples

TypeScript
Copied!
1test('daysBetween - same date', () => {
2  const d = new Date('2023-01-01');
3  expect(daysBetween(d, d)).toBe(0);
4});
5
6test('daysBetween - one day apart', () => {
7  const d1 = new Date('2023-01-01');
8  const d2 = new Date('2023-01-02');
9  expect(daysBetween(d1, d2)).toBe(1);
10});
11
12test('daysBetween - multiple days apart', () => {
13  const d1 = new Date('2023-01-01');
14  const d2 = new Date('2023-01-10');
15  expect(daysBetween(d1, d2)).toBe(9);
16});
17
18test('daysBetween - order does not matter', () => {
19  const d1 = new Date('2023-01-10');
20  const d2 = new Date('2023-01-01');
21  expect(daysBetween(d1, d2)).toBe(9);
22});
23
24test('daysBetween - accounts for time differences', () => {
25  const d1 = new Date('2023-01-01T23:59:59');
26  const d2 = new Date('2023-01-02T00:00:01');
27  expect(daysBetween(d1, d2)).toBe(1);
28});

Common Use Cases

  • Countdowns and Scheduling

    Calculate days remaining until deadlines, events, or appointments.

  • Subscription or Trial Logic

    Determine how many days have passed since activation or registration.

  • Age or Tenure Calculations

    Measure full days between birthdays, hire dates, or other key events.

  • Analytics and Reporting

    Compare timestamps in logs or datasets to calculate usage gaps or activity spans.

  • Validation Rules

    Enforce date-based conditions like “minimum 7 days apart” or “not older than 30 days”.

Codebase: Utilities -> Dates -> daysBetween | Yevhen Klymentiev