Skip to content

Tempo Cookbook ​

A collection of recipes for solving common date and time challenges using Tempo.

Table of Contents ​

  1. The Basics
  2. Parsing Challenges
  3. Manipulation and Calculations
  4. Timezones and Locales
  5. Business Logic and Terms
  6. Formatting and Localization
  7. Interoperability

The Basics ​

How do I get the current date and time? ​

Use the static Tempo.now() factory method to capture the current system date and time:

typescript
const now = Tempo.now();
console.log(now.toString()); // e.g. "2026-07-31T14:42:11+10:00[Australia/Sydney]"

Get "Now" in UTC or a specific time zone ​

Pass an options object directly to Tempo.now():

typescript
const utcNow = Tempo.now({ timeZone: 'UTC' });
const tokyoNow = Tempo.now({ timeZone: 'Asia/Tokyo' });

How do I format a date for my UI? ​

Use the placeholder syntax in the .format() method.

typescript
const t = new Tempo('2024-12-25');
t.format('{dd} {mon} {yyyy}');  // "25 December 2024"
t.format('{h12}:{mi}');         // "12:00am"

How do I check if a date is valid? ​

typescript
const t = new Tempo('invalid-date');
if (t.isValid) {
  // ...
}

Global Configuration ​

You can initialize global defaults that apply to all future Tempo instances.

typescript
Tempo.init({
  timeZone: 'UTC',
  locale: 'en-GB',
  silent: true
});

👉 Learn More: Configuration Guide


Parsing Challenges ​

Parsing "Ambiguous" Digits (US vs UK) ​

Tempo intelligently resolves ambiguous dates like 04012026 based on your timezone.

typescript
const us = new Tempo('04012026', { timeZone: 'America/New_York' });
console.log(us.format('{mon} {dd}')); // "April 01"

👉 Learn More: Ambiguity Resolution Guide

Handling Relative Strings ​

Tempo natively understands human-readable offsets.

typescript
new Tempo('yesterday');
new Tempo('next Friday');
new Tempo('2 weeks ago');
new Tempo('tomorrow afternoon');

👉 Learn More: You can seamlessly localize relative phrases (e.g. next to prochain) by reading the Internationalized Parsing Guide.

Parsing Unix Timestamps ​

Tempo handles both milliseconds (Number) and nanoseconds (BigInt).

typescript
new Tempo(1716163200000);         // Milliseconds
new Tempo(1716163200000000000n);  // Nanoseconds

Manipulation and Calculations ​

Add or Subtract Time ​

Tempo instances are immutable; add() returns a new instance.

typescript
const deadline = new Tempo().add({ days: 7, hours: 2 });
const past = new Tempo().add({ months: -1 });

// You can also step by semantic Terms using the `#` prefix!
const t1 = new Tempo('2024-05-15'); // Middle of Q2
const t2 = t1.add({ '#quarter': 1 }); // Middle of Q3: "2024-08-14" (approx)

Jumping to Boundaries (start, mid, end) ​

The .set() method allows you to jump to the boundaries of native units (like months or years) or semantic Terms (using the # prefix). You can specify whether to land on the inclusive start, inclusive end, or the exact center.

typescript
// Native Units
const monthStart = new Tempo().set({ month: 'start' });

// Semantic Terms (Lands on 30-Sep 23:59:59.999... Inclusive End)
const qtrEnd = new Tempo('2024-07-15').set({ '#quarter': 'end' });

// Lands on the arithmetic nanosecond midpoint of the period
const qtrMid = new Tempo().set({ '#quarter': 'mid' });

Slick Object Mutations ​

You can navigate relative to your current date by using Slick Shorthand operators directly inside .set(). Use the snippet shorthand keys (yy, mm, ww, dd, wkd, etc.) and provide a string payload containing a directional modifier:

typescript
const t = new Tempo('2024-05-20'); // Monday
t.set({ mm: '>2' });               // July 20th
t.set({ wkd: '>Fri' });            // May 24th

👉 Learn More: To read about advanced chaining, order-of-operations, and architectural limitations, see the Slick Object Mutations Deep Dive.

How long until a deadline? (until) ​

typescript
const t = new Tempo();
const daysLeft = t.until('2025-01-01', 'days');
console.log(`${daysLeft} days remaining`);

Relative Time (since) ​

Generate human-readable relative time strings instantly.

typescript
const t = new Tempo('yesterday');
console.log(t.since()); // "1d ago"

Comparing & Checking Equality (compare, equals) ​

Compare two dates chronologically—even across different timezones—or test equality at instant or unit precision:

typescript
const nyc    = new Tempo('2026-05-10T18:00:00', { timeZone: 'America/New_York' }); // 22:00 UTC
const london = new Tempo('2026-05-10T23:00:00', { timeZone: 'Europe/London' });    // 22:00 UTC (same instant)
const tokyo  = new Tempo('2026-05-11T09:00:00', { timeZone: 'Asia/Tokyo' });       // 00:00 UTC (May 10 20:00 in NYC)

// Exact instant comparison (returns -1 | 0 | 1)
Tempo.compare(nyc, london);              // 0  (same instant across timezones)
Tempo.compare(nyc, tokyo);               // -1 (nyc is 2 hours earlier)
Tempo.compare(nyc);                      // Compare `nyc` against now (omitted 2nd arg)

// Granular comparison projected into the 1st operand's timezone
Tempo.compare(nyc, tokyo, 'day');        // 0  (both fall on May 10 in America/New_York; 'date' also accepted)
Tempo.compare(nyc, tokyo, { unit: 'hour' }); // -1 (18:00 vs 20:00 in New York)

// Exact instant & unit-level equality
Tempo.equals(nyc, london);               // true (same instant across timezones)
nyc.equals(tokyo, 'day');                // true (same calendar day in New York)
nyc.equals('2026-05-10T23:00:00', { unit: 'day' }); // true (raw string inherits nyc's timezone)
nyc.equals('week');                      // Is `nyc` in the current ISO week? (compares against now)

👉 Learn More: See Comparisons & Predicates for supported units, { unit } options, t.is.* predicates, and timezone projection rules.


Timezones and Locales ​

Convert Time to Another Zone ​

typescript
const nyc = new Tempo('2024-05-20 10:00', { timeZone: 'America/New_York' });
const london = nyc.set({ timeZone: 'Europe/London' });

console.log(nyc.format('{hh}:{mi}'));    // "10:00"
console.log(london.format('{hh}:{mi}')); // "15:00"

Dynamic / Multi-Tenant Context (Functional Options) ​

Context options (timeZone, locale, calendar, sphere) accept supplier functions (() => string). Tempo resolves suppliers at instantiation time to construct an immutable, frozen instance:

typescript
import { AsyncLocalStorage } from 'node:async_hooks';

const requestContext = new AsyncLocalStorage<{ timeZone: string; locale: string }>();

// Configure dynamic suppliers that evaluate against current request context
const t = new Tempo('now', {
  timeZone: () => requestContext.getStore()?.timeZone || 'UTC',
  locale: () => requestContext.getStore()?.locale || 'en-US'
});

👉 Learn More: See the Configuration Guide for details on functional options and immutability guarantees.


Business Logic and Terms ​

Is it the weekend? ​

Use the built-in t.is.weekend() and t.is.weekday() predicates — they are automatically locale-aware (backed by Intl.Locale.prototype.getWeekInfo() and Tempo's regional fallback resolver, the same data exposed by t.intl.info.weekend), so they adapt to regional weekend days such as Friday & Saturday ([5, 6]) in ar-SA:

typescript
// Standard weekend ([6, 7] for Saturday & Sunday in en-US)
const us = new Tempo('2026-12-04', { locale: 'en-US' }); // Friday
us.is.weekend(); // false
us.is.weekday(); // true

// Regional weekend ([5, 6] for Friday & Saturday in ar-SA)
const sa = new Tempo('2026-12-04', { locale: 'ar-SA' }); // Friday
sa.is.weekend(); // true
sa.is.weekday(); // false

If you need the raw ISO day-of-week numbers (1 = Monday … 7 = Sunday), inspect t.dow or t.intl.info.weekend directly. See the Comparisons & Predicates Guide for all built-in t.is.* checks (leapYear, today, past, future, dst, between, and custom predicates).

What Calendar Quarter are we in? ​

Using the qtr Term plugin (term.qtr is a convenient alias for the full term.quarter property).

typescript
const t = new Tempo();
console.log(`Current Quarter: ${t.term.qtr}`); // "Q1", "Q2", etc.

Hemispheric Seasons ​

Tempo Terms are hemisphere-aware.

typescript
const sydney = new Tempo('2024-07-01', { sphere: 'south' });
console.log(sydney.term.szn); // "Winter"

const london = new Tempo('2024-07-01', { sphere: 'north' });
console.log(london.term.szn); // "Summer"

// or even via the timeZone setting
console.log(new Tempo({ timeZone: 'America/New_York' }).term.szn); // "Summer"
console.log(new Tempo({ timeZone: 'Australia/Sydney' }).term.szn); // "Winter"

Formatting and Localization ​

Semantic Formatting ​

Use specific Term tokens like {#quarter} or {#season} to automatically embed a Term's label (or key) into a format string.

typescript
const t = new Tempo();
console.log(t.format('We are currently in the {#quarter}')); // "We are currently in the First Quarter"

Format Modifiers & Localization ​

Format strings support chained colon-modifiers (e.g., :upper, :locale, :ord) to dynamically change the presentation casing or delegate to the native Intl API. You can stack them to get the exact presentation required!

typescript
const t = new Tempo('2024-05-15 15:30', { locale: 'fr-FR' });

t.format('{mon:upper}');             // "MAY" (English Default -> UpperCase)
t.format('{mon:long}');              // "mai" (Native French Intl output via styling bridge)
t.format('{mon:long:upper} {dd}');   // "MAI 15" (Native French Intl output)

👉 Learn More: See the Smart Formatting Guide for the complete list of available modifiers.

TIP

Tired of typing styling modifiers? If you find yourself repeatedly writing :long or :short for the same localized date structure, save it to the global FORMATS registry! This creates a clean, reusable shortcut:

typescript
Tempo.init({
    locale: 'fr-FR',
    registry: {
        formats: {
            'ui-date': '{wkd:long}, {dd:raw} {mon:long} {yyyy}'
        }
    }
});

t.format('ui-date'); // Resolved with all modifiers intact!

Note: Format keys are resolved case-sensitively from the global registry.formats object. If the requested key is not found, Tempo will simply treat the provided string as a literal layout string rather than throwing an error.

👉 Learn More: To build custom zero-overhead logic evaluators (like Fiscal Years or native Intl bridges), read the Custom Format Tokens Deep Dive.

👉 Learn More:


Ticker Plugin ​

The Ticker engine is a community plugin for precisely driving business logic (like recurring billing or reporting cycles) on specific date boundaries.

typescript
// Drive internal reporting precisely when a new quarter begins
await using quarterly = Tempo.ticker({ '#quarter': 1 });

for await (const t of quarterly) {
  generateReport(t.term.qtr);
}

👉 Learn More: See the Ticker Plugin Documentation for detailed configuration, term-driven intervals, and await using syntax requirements.


Format & Parse Dialects Plugin (Moment, Luxon, SQL, POSIX, PHP) ​

If you are migrating existing code or layouts from Moment.js, Luxon, date-fns, POSIX strftime, PHP, or SQL, use the @tempo-kit/plugin-dialects community plugin.

typescript
// Zero-config drop-in import automatically mounts dialect shims:
import '@tempo-kit/plugin-dialects/install';

const t = new Tempo('2026-10-24T15:30:00');

// Luxon convenience shim (.toFormat)
t.toFormat('yyyy-MM-dd HH:mm:ss');          // "2026-10-24 15:30:00"

// LDML & Moment parsing
Tempo.fromFormat('2026-10-24', 'yyyy-MM-dd'); // LDML parsing via Luxon shim
Tempo.dialects.parse('2026-10-24', 'YYYY-MM-DD', 'moment'); // Moment layout parsing

// Direct dialect formatters
t.dialects.sql('YYYY-MM-DD HH24:MI:SS');     // Oracle / PostgreSQL TO_CHAR
t.dialects.php('Y-m-d H:i:s');               // PHP date()
t.dialects.go('2006-01-02 15:04:05');        // Go reference layout

👉 Learn More: See the Dialects Plugin Documentation for full token specifications, multi-candidate parsing fallbacks, and cross-ecosystem translation.


Interoperability ​

Converting to / from Native Date ​

typescript
const date = new Tempo().toDate();
const tempo = new Tempo(new Date());

Converting to Temporal Objects ​

typescript
const zdt = new Tempo().toDateTime();    // Temporal.ZonedDateTime (or .toDateTime())
const instant = new Tempo().toInstant(); // Temporal.Instant
const pdt = new Tempo().toPlainDate();   // Temporal.PlainDate

Sorting an array of Tempos ​

Tempo.compare compares exact instants on the timeline, so standard sorting automatically handles any mix of timezones and calendars with zero manual alignment:

typescript
const dates = [
  new Tempo('2026-05-11T09:00:00', { timeZone: 'Asia/Tokyo' }),       // May 11 00:00 UTC
  new Tempo('2026-05-10T18:00:00', { timeZone: 'America/New_York' }), // May 10 22:00 UTC (2h earlier)
  new Tempo('2026-05-10T23:00:00', { timeZone: 'Europe/London' }),    // May 10 22:00 UTC (same instant as NYC)
];

dates.sort(Tempo.compare); // Chronological order across mixed timezones

When sorting at a coarser unit granularity (such as 'day' or 'month'), pass an anchor or explicit timeZone / calendar in CompareOptions so Tempo evaluates every pair against one consistent reference frame:

typescript
// Option A: Anchor mixed items to a reference Tempo (e.g. dates[0])
dates.sort((a, b) => Tempo.compare(a, b, { unit: 'day', anchor: dates[0] }));

// Option B: Normalize evaluations to an explicit fixed timezone & calendar (order-independent)
dates.sort((a, b) => Tempo.compare(a, b, { unit: 'day', timeZone: 'UTC', calendar: 'iso8601' }));

Granular Sorting: anchor vs. Fixed Frame

Without anchor or timeZone / calendar, Tempo.compare(a, b, 'day') evaluates in a's timezone and calendar—which is asymmetric if .sort() swaps mixed-zone elements freely. Passing anchor: dates[0] is convenient when the first item defines your reference zone, though different initial array orders can change which element acts as the anchor; specifying a fixed { timeZone, calendar } guarantees deterministic results regardless of input order.

Released under the MIT License.