differenceInDays
Calculate the difference between two dates in days
Returns the number of days between two datetimes. Uses calendar-aware calculation, which means it properly handles DST transitions where days can be 23, 24, or 25 hours long.
Signature
function differenceInDays(
laterDate: Temporal.Instant | Temporal.ZonedDateTime,
earlierDate: Temporal.Instant | Temporal.ZonedDateTime,
options?: DifferenceOptions
): number
interface DifferenceOptions {
fractional?: boolean; // default false — truncates toward zero
}Parameters
| Parameter | Type | Description |
|---|---|---|
laterDate | Temporal.Instant | Temporal.ZonedDateTime | The later datetime |
earlierDate | Temporal.Instant | Temporal.ZonedDateTime | The earlier datetime |
options.fractional | boolean | Return the precise fractional value instead of truncating toward zero (default: false) |
Returns
The number of days between the two datetimes, truncated toward zero by default. Pass { fractional: true } to get the precise fractional value.
Examples
Basic usage
import { differenceInDays } from '@gobrand/tiempo';
const later = Temporal.Instant.from('2025-01-25T12:00:00Z');
const earlier = Temporal.Instant.from('2025-01-20T12:00:00Z');
differenceInDays(later, earlier); // 5With ZonedDateTime
const laterZoned = Temporal.ZonedDateTime.from('2025-01-25T15:00:00-05:00[America/New_York]');
const earlierZoned = Temporal.ZonedDateTime.from('2025-01-20T15:00:00-05:00[America/New_York]');
differenceInDays(laterZoned, earlierZoned); // 5Handles DST transitions correctly
const afterDst = Temporal.ZonedDateTime.from('2025-03-10T12:00:00-04:00[America/New_York]');
const beforeDst = Temporal.ZonedDateTime.from('2025-03-08T12:00:00-05:00[America/New_York]');
differenceInDays(afterDst, beforeDst); // 2 (calendar days, not 48 hours)Fractional results
By default the result is truncated toward zero. Pass { fractional: true } for the precise value.
const later = Temporal.Instant.from('2025-01-21T12:00:00Z');
const earlier = Temporal.Instant.from('2025-01-20T00:00:00Z');
differenceInDays(later, earlier); // 1 (truncated)
differenceInDays(later, earlier, { fractional: true }); // 1.5 (precise)Common Patterns
Time until event
import { differenceInDays, differenceInHours, differenceInMinutes } from '@gobrand/tiempo';
function timeUntil(eventDate: Temporal.ZonedDateTime): string {
const now = Temporal.Now.zonedDateTimeISO();
const days = differenceInDays(eventDate, now);
if (days > 1) return `${days} days`;
const hours = differenceInHours(eventDate, now);
if (hours > 1) return `${hours} hours`;
const minutes = differenceInMinutes(eventDate, now);
return `${minutes} minutes`;
}