tiempo

differenceInSeconds

Calculate the difference between two dates in seconds

Returns the number of seconds between two datetimes.

Signature

function differenceInSeconds(
  laterDate: Temporal.Instant | Temporal.ZonedDateTime,
  earlierDate: Temporal.Instant | Temporal.ZonedDateTime,
  options?: DifferenceOptions
): number

interface DifferenceOptions {
  fractional?: boolean; // default false — truncates toward zero
}

Parameters

ParameterTypeDescription
laterDateTemporal.Instant | Temporal.ZonedDateTimeThe later datetime
earlierDateTemporal.Instant | Temporal.ZonedDateTimeThe earlier datetime
options.fractionalbooleanReturn the precise fractional value instead of truncating toward zero (default: false)

Returns

The number of seconds between the two datetimes, truncated toward zero by default. Pass { fractional: true } to get the precise fractional value.

Examples

import { differenceInSeconds } from '@gobrand/tiempo';

const later = Temporal.Instant.from('2025-01-20T10:01:30Z');
const earlier = Temporal.Instant.from('2025-01-20T10:00:00Z');

differenceInSeconds(later, earlier); // 90

Fractional results

By default the result is truncated toward zero. Pass { fractional: true } for the precise value.

const later = Temporal.Instant.from('2025-01-20T10:00:01.500Z');
const earlier = Temporal.Instant.from('2025-01-20T10:00:00Z');

differenceInSeconds(later, earlier);                       // 1   (truncated)
differenceInSeconds(later, earlier, { fractional: true }); // 1.5 (precise)

Common Patterns

Format duration

import {
  differenceInHours,
  differenceInMinutes,
  differenceInSeconds,
} from '@gobrand/tiempo';

function formatDuration(
  start: Temporal.ZonedDateTime,
  end: Temporal.ZonedDateTime
): string {
  const totalSeconds = differenceInSeconds(end, start);
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;

  return `${hours}h ${minutes}m ${seconds}s`;
}

On this page