Skip to content

Comparisons & Predicates ​

Comparing dates, sorting timelines, checking whether an event falls inside a billing window, or testing calendar states like weekends and Daylight Saving Time are among the most common operations in any date-time application.

Tempo organizes these into three complementary surfaces:

  • Tempo.compare(a, b, unitOrOptions?) — Three-way comparator (-1 | 0 | 1) designed for sorting (dates.sort(Tempo.compare)).
  • Tempo.equals(a, b, unitOrOptions?) / t.equals(other?, unitOrOptions?) — Non-throwing equality checks at exact instant or calendar-unit granularity.
  • t.is.* — A lazy-memoized, frozen, extensible predicate namespace for readable relational checks, interval bounds (between), 7 built-in calendar/state checks, and your own domain predicates via config.registry.predicates.

Sorting & Three-Way Comparison (Tempo.compare) ​

Tempo.compare(a, b, unitOrOptions?) returns -1 if a is earlier than b, 0 if equal, or 1 if later. Because its signature matches Array.prototype.sort and compares exact instants (epoch.ns) by default, passing Tempo.compare sorts events across different timezones in true chronological order — even when their wall-clock times appear out of order:

typescript
import { Tempo } from 'tempo-kit';

const events = [
  new Tempo('2026-06-15T09:00:00', { timeZone: 'America/New_York' }), // 13:00Z
  new Tempo('2026-06-15T20:00:00', { timeZone: 'Australia/Sydney' }), // 10:00Z
  new Tempo('2026-06-15T20:30:00', { timeZone: 'Asia/Tokyo' }),       // 11:30Z
  new Tempo('2026-06-15T12:00:00', { timeZone: 'UTC' }),              // 12:00Z
];

events.sort(Tempo.compare).map((t) => `${t.tz} (${t.iso})`);
// → [
//   'Australia/Sydney (2026-06-15T10:00:00Z)',
//   'Asia/Tokyo (2026-06-15T11:30:00Z)',
//   'UTC (2026-06-15T12:00:00Z)',
//   'America/New_York (2026-06-15T13:00:00Z)',
// ]

By default, Tempo.compare() compares exact instants (epoch.ns), so two Tempo values in different timezones that represent the same moment return 0. Pass a CompareUnit or CompareOptions object to compare at calendar/time granularity or within a specific timezone/calendar frame:

typescript
const morning = new Tempo('2026-06-15T08:00:00Z');
const evening = new Tempo('2026-06-15T20:00:00Z');

Tempo.compare(morning, evening);          // → -1 (exact instant)
Tempo.compare(morning, evening, 'day');   // →  0 (same calendar day)
Tempo.compare(morning, evening, 'hour');  // → -1 (08:00 < 20:00)

// Evaluate calendar-day boundary in a specific timezone
const lateUtc  = new Tempo('2026-06-15T22:00:00Z');
const earlyUtc = new Tempo('2026-06-15T02:00:00Z');

Tempo.compare(lateUtc, earlyUtc, { unit: 'day', timeZone: 'UTC' });              // → 0
Tempo.compare(lateUtc, earlyUtc, { unit: 'day', timeZone: 'Australia/Sydney' }); // → 1 (June 16 vs June 15)

NOTE

Tempo.compare() throws a RangeError if either operand (or options.anchor) is invalid, matching Temporal.*.compare(). For non-throwing boolean checks, use Tempo.equals(), t.equals(), or t.is.*.


Equality (Tempo.equals & t.equals) ​

Both Tempo.equals(a, b, unitOrOptions?) and instance t.equals(other?, unitOrOptions?) return boolean and never throw on invalid inputs (returning false instead):

typescript
const a = new Tempo('2026-06-15T10:00:00Z');
const b = new Tempo('2026-06-15T20:00:00+10:00[Australia/Sydney]');
const c = new Tempo('2026-06-15T18:30:00Z');

a.equals(b);          // → true  (same exact instant)
a.equals(c);          // → false (different instants)
a.equals(c, 'day');   // → true  (same calendar day)

// Omitting `other` compares against `now`
new Tempo().equals('day'); // → true

Relational Predicates (t.is.*) ​

Every Tempo instance exposes a lazy-memoized, Object.freeze()-protected t.is namespace. Accessing t.is allocates once per instance (t.is === t.is) and incurs O(0) overhead on instances that never read it.

MethodMeaningDefault (other omitted)
t.is.before(other?, unitOrOpts?)t < otherCompares against now
t.is.after(other?, unitOrOpts?)t > otherCompares against now
t.is.same(other?, unitOrOpts?)t === otherCompares against now
t.is.sameOrBefore(other?, unitOrOpts?)t ≤ otherCompares against now
t.is.sameOrAfter(other?, unitOrOpts?)t ≥ otherCompares against now
typescript
const launch = new Tempo('2026-06-15T10:00:00Z');
const cutoff = new Tempo('2026-06-15T14:30:00Z');

launch.is.before(cutoff);          // → true
launch.is.after(cutoff);           // → false
launch.is.same(cutoff, 'day');     // → true
launch.is.sameOrBefore(cutoff);    // → true
cutoff.is.sameOrAfter(launch);     // → true

// Single-argument unit shorthand compares against `now`
new Tempo().is.same('day');        // → true
new Tempo('2000-01-01').is.before('year'); // → true

All t.is.* predicates return false without throwing when this or any comparison operand is invalid.


Range Checks (t.is.between & Tempo.enums.BOUNDS) ​

t.is.between() checks whether this falls inside a bounded or open-ended range. It accepts either two positional endpoints or an Interval / { start, end } object:

typescript
const start = new Tempo('2026-06-01T00:00:00Z');
const mid   = new Tempo('2026-06-15T12:00:00Z');
const end   = new Tempo('2026-07-01T00:00:00Z');

// Positional endpoints (default: half-open '[)' → start ≤ t < end)
mid.is.between(start, end);   // → true
start.is.between(start, end); // → true
end.is.between(start, end);   // → false

// Interval or { start, end } range overload
const june = new Tempo.Interval(start, end);
mid.is.between(june);         // → true
mid.is.between({ start, end }); // → true

Boundary Inclusivity (Tempo.enums.BOUNDS) ​

Tempo.enums.BOUNDS defines the four standard mathematical interval modes. The default is halfOpen ('[)'), matching Interval slicing, Temporal range conventions, and contiguous partitioning (so adjacent months [Jun 1, Jul 1) and [Jul 1, Aug 1) never double-count midnight on July 1):

Enum MemberStringCondition
Tempo.enums.BOUNDS.halfOpen (default)'[)'start ≤ t < end
Tempo.enums.BOUNDS.inclusive'[]'start ≤ t ≤ end
Tempo.enums.BOUNDS.exclusive'()'start < t < end
Tempo.enums.BOUNDS.leftOpen'(]'start < t ≤ end

Pass bounds inside the options object (optionally combined with unit, timeZone, calendar, or anchor):

typescript
const { inclusive, exclusive, leftOpen } = Tempo.enums.BOUNDS;

end.is.between(start, end, { bounds: inclusive }); // → true
start.is.between(start, end, { bounds: exclusive }); // → false
end.is.between(start, end, { bounds: leftOpen }); // → true

// Combine unit granularity with inclusive bounds
const july1Evening = new Tempo('2026-07-01T20:00:00Z');
july1Evening.is.between(start, end, { unit: 'day', bounds: inclusive }); // → true

Open-Ended & Inverted Ranges ​

  • Open-ended boundaries: Pass null for start or end to leave that side unbounded (t.is.between(null, cutoff) or t.is.between({ start, end: null })).
  • Inverted ranges: If both endpoints are bounded and start > end, between() returns false.
  • Invalid bounds string: Passing an unrecognized bounds value throws a RangeError.

Built-In Calendar & State Checks ​

t.is ships with 7 built-in calendar and temporal state predicates (all zero-argument methods returning boolean):

MethodBehavior
t.is.leapYear()true if this's year is a leap year in its active calendar (zdt.inLeapYear).
t.is.weekend()Locale-aware weekend check using Intl.Locale weekInfo.weekend (defaults to Sat/Sun [6, 7]; e.g., Fri/Sat [5, 6] for ar-SA and he-IL).
t.is.weekday()Logical inverse of t.is.weekend() (returns false on invalid instances).
t.is.today()Dynamic check: true if this falls on the same calendar day as now in this's timezone.
t.is.past()Dynamic check: true if this.epoch.ns < now.epoch.ns.
t.is.future()Dynamic check: true if this.epoch.ns > now.epoch.ns.
t.is.dst()true if this is currently observing Daylight Saving Time in its timezone (false for UTC and fixed-offset zones).
typescript
// Leap year
new Tempo('2024-06-01').is.leapYear(); // → true
new Tempo('2026-06-01').is.leapYear(); // → false

// Locale-aware weekend / weekday
new Tempo('2026-06-12', { locale: 'en-US' }).is.weekend(); // → false (Friday in US)
new Tempo('2026-06-12', { locale: 'ar-SA' }).is.weekend(); // → true  (Friday in Saudi Arabia)

// Dynamic relative checks
new Tempo().is.today();                       // → true
new Tempo().subtract({ days: 1 }).is.past();  // → true
new Tempo().add({ days: 1 }).is.future();     // → true

// Daylight Saving Time
new Tempo('2026-01-15T12:00:00', { timeZone: 'Australia/Sydney' }).is.dst(); // → true  (AEDT +11)
new Tempo('2026-07-15T12:00:00', { timeZone: 'Australia/Sydney' }).is.dst(); // → false (AEST +10)
new Tempo('2026-01-15T12:00:00Z', { timeZone: 'UTC' }).is.dst();             // → false

Extensible Custom Predicates (config.registry.predicates) ​

You can register domain-specific predicates onto t.is globally via Tempo.init() or in an isolated sandbox via Tempo.extend():

typescript
import { Tempo } from 'tempo-kit';

const BizTempo = Tempo.extend({
  registry: {
    predicates: {
      businessHour: (t) => t.is.weekday() && t.hh >= 9 && t.hh < 17,
      olderThan: (t, years: number) => t.is.before(new Tempo().subtract({ years })),
    },
  },
});

const mondayMorning = new BizTempo('2026-06-15T10:30:00', { locale: 'en-US' });
mondayMorning.is.businessHour(); // → true
mondayMorning.is.olderThan(5);   // → false

TypeScript Autocomplete (TempoPredicateRegistry) ​

Augment TempoPredicateRegistry in your app or plugin's .d.ts file to get full IDE autocomplete and type checking for custom predicates:

typescript
import 'tempo-kit';

declare module 'tempo-kit' {
  interface TempoPredicateRegistry {
    businessHour(): boolean;
    olderThan(years: number): boolean;
  }
}

Safety & Override Rules ​

  • Core relational operators are locked: The 6 structural operators (before, after, same, sameOrBefore, sameOrAfter, between) cannot be overwritten by registry.predicates.
  • State predicates are sandbox-overridable: The 7 built-in pure state predicates (leapYear, weekend, weekday, today, past, future, dst) are seeded in Default.registry.predicates, so you can shadow them inside a Tempo.extend() sandbox (e.g., overriding weekend: (t) => [5, 6, 7].includes(t.dow) for a 4-day workweek, which weekday() automatically reflects) without affecting the global Tempo class.
  • Prototype safety: Unsafe keys (__proto__, constructor, prototype) are ignored via isSafeKey().
  • Boolean coercion & invalid-instance guard: Return values are coerced via Boolean(...), and invalid Tempo instances return false without invoking the custom predicate.
  • Sandbox isolation: Predicates registered via Tempo.extend({ registry: { predicates } }) stay scoped to that sandbox and do not leak onto the global Tempo class.

Released under the MIT License.