Skip to content

Time

Durations, timestamps, civil dates and times, and IANA time zones.

Atoll separates elapsed spans from absolute instants, and both from civil calendar values. Every core temporal type is a @builtin struct over a single int, so it costs one machine word and crosses the SQL temporal boundary with no unit conversion.

All of it is the standard library’s time module, a module like json rather than a root name. A file that uses it says import time and writes each name through the module: time.Duration.of_seconds(30), time.DateTime.now(), time.sleep(d), a field typed time.Duration. The sentences and tables below call the types by their short names. The deadline names the concurrency pages use — time.after(d), Deadline, Timed[T] — are this module’s too; see Select.

Type Backing value Meaning
Duration nanoseconds A signed span — “how long”
DateTime Unix-epoch microseconds, UTC An instant
Date days since 1970-01-01 A calendar day
Time microseconds since midnight A time of day
TimeZone IANA zone id A zone rule set
ZonedDateTime local microseconds + offset An instant seen from a zone

Durations

Every constructor names its unit. There are no bare-number durations.

import time

fn main() void {
    timeout := time.Duration.of_seconds(30)
    retry := time.Duration.of_millis(250)
    combined := timeout.plus(retry)
    println("${combined.total_millis()} ms")
}

The full constructor set is of_nanos, of_micros, of_millis, of_seconds, of_minutes, of_hours, of_days. A Duration is nanoseconds, as Go’s is, so every one of them is exact — time.Duration.of_nanos(1500) is 1500 nanoseconds — and an int of them spans ±292 years.

import time

fn main() void {
    println("${time.Duration.of_nanos(1500).total_micros()}")   // 1
    println("${time.Duration.of_nanos(1500).total_nanos()}")    // 1500
    println("${time.Duration.of_days(2).total_hours()}")        // 48
    println("${time.Duration.of_millis(1500).total_seconds()}") // 1 — truncates
}

Every total_* accessor truncates toward zero. Arithmetic and comparison are named methods:

import time

fn main() void {
    short := time.Duration.of_millis(250)
    long := time.Duration.of_seconds(30)

    println("${long.minus(short).total_millis()}")  // 29750
    println("${short.times(4).total_seconds()}")    // 1
    println("${long.negated().is_negative()}")      // true
    println("${time.Duration.of_micros(0).is_zero()}")   // true
    println("${short.less_than(long)}")             // true
    println("${long.equals(time.Duration.of_minutes(1))}") // false
}

The comparison operators work directly — Comparable is derived for a Duration the way it is for any struct, and it compares the nanosecond field:

import time

fn main() void {
    a := time.Duration.of_seconds(30)
    b := time.Duration.of_seconds(1)
    println("${b < a}")   // true
    println("${a == a}")  // true
}

So do the arithmetic operators, each one the method of its name: a + b is a.add(b) and a - b is a.sub(b), and a Duration scales by a whole number, d * n and d / n, the division truncating toward zero:

import time

fn main() void {
    a := time.Duration.of_seconds(30)
    b := time.Duration.of_seconds(1)
    println("${(a + b).total_seconds()}")  // 31
    println("${(a - b).total_seconds()}")  // 29
    println("${(b * 4).total_seconds()}")  // 4
    println("${(a / 4).total_millis()}")   // 7500
}

An operator’s right side is its method’s argument, which keeps the units honest: there is no meaning to give Duration * Duration, and a bare number is no Duration to add:

import time

fn main() void {
    a := time.Duration.of_seconds(30)
    println("${(a + 1).total_seconds()}")
}

plus, minus, times and negated say the same by name.

Instants

DateTime is a UTC instant measured from the Unix epoch. time.DateTime.now() reads the host wall clock, in nanoseconds, floored to the instant’s microsecond; the read answers directly and does not suspend.

import time

fn main() void {
    started := time.DateTime.now()
    deadline := started.plus(time.Duration.of_seconds(30))
    elapsed := time.DateTime.now().diff(started)

    println("elapsed ${elapsed.total_micros()} us")
    println("overdue = ${time.DateTime.now().is_after(deadline)}")
}

plus and minus take a Duration; diff returns one. is_before, is_after, and equals compare two instants.

At protocol boundaries, convert through the epoch accessors. Each from_epoch_* constructor has a matching epoch_* reader:

import time

fn main() void {
    t := time.DateTime.from_epoch_seconds(1700000000)

    println("${t.epoch_seconds()}")  // 1700000000
    println("${t.epoch_millis()}")   // 1700000000000
    println("${t.epoch_micros()}")   // 1700000000000000
    println("${t.epoch_nanos()}")    // 1700000000000000000
    println("${t.epoch_days()}")     // 19675

    same := time.DateTime.from_epoch_millis(1700000000000)
    println("${same.equals(t)}")     // true
}

An instant is microseconds — the SQL wire’s Timestamp, and ±292,000 years where nanoseconds would stop at 1678 and 2262 — so from_epoch_nanos floors to the microsecond, and so does moving an instant by a Duration: plus moves it by the whole microseconds in the span, rounded toward the past, and minus(d) is plus(d.negated()). diff is exact. epoch_millis, epoch_seconds and epoch_days round toward the past as well, so one microsecond before the epoch is millisecond -1, second -1 and day -1, and an instant built back from any of them never lands after the one it was read from.

UTC calendar components come straight off the instant, and date() / time() project it onto the civil types:

import time

fn main() void {
    t := time.DateTime.from_epoch_seconds(1700000000)
    println("${t.year()}-${t.month()}-${t.day()} ${t.hour()}:${t.minute()}:${t.second()}")

    d := t.date()
    clock := t.time()
    println("day ${d.epoch_days()}, ${clock.micros_of_day()} us into the day")
}

time.DateTime.now() is a wall clock, not a monotonic timer. A host clock adjustment between two calls can make the difference negative; check with is_negative() before trusting an elapsed span.

Civil values

Date holds a calendar day with no time and no zone. Day arithmetic is explicit — there is no month or year arithmetic in the current surface.

import time

fn main() void {
    today := time.Date.today()
    next_week := today.plus_days(7)
    yesterday := today.minus_days(1)

    println("${next_week.year()}-${next_week.month()}-${next_week.day()}")
    println("${yesterday.is_before(today)}")   // true
    println("${today.equals(today)}")          // true
}

time.Date.from_epoch_days and epoch_days convert to and from the day count since 1970-01-01:

import time

fn main() void {
    epoch_day := time.Date.from_epoch_days(0)
    println("${epoch_day.year()}-${epoch_day.month()}-${epoch_day.day()}")  // 1970-1-1
}

Time is a time of day, built from hour/minute/second:

import time

fn main() void {
    t := time.Time.of_hms(9, 30, 15)
    println("${t.hour()}:${t.minute()}:${t.second()}")
    println("${t.micros_of_day()}")
}

time.Time.of_hms does not validate its arguments — it just multiplies. Range-check untrusted hour, minute, and second input yourself before constructing one.

Time zones

time.TimeZone.utc() needs no lookup. time.TimeZone.of(name) resolves an IANA name through the host and returns None for an unknown one, so it is an Option:

import time

fn main() void {
    zone := time.TimeZone.of("Asia/Kuala_Lumpur")
    match zone {
        Some(z) => {
            local := time.DateTime.now().in_zone(z)
            println("${local.hour()}:${local.minute()}")
        }
        None => println("unknown zone name")
    }
}

When a fallback is acceptable, ?? is shorter:

import time

fn main() void {
    zone := time.TimeZone.of("America/New_York") ?? time.TimeZone.utc()
    local := time.DateTime.now().in_zone(zone)
    println("${local.year()}-${local.month()}-${local.day()} ${local.hour()}h")
}

in_zone yields a ZonedDateTime whose accessors read local components. to_utc() recovers the original instant and offset() reports the zone’s UTC offset at that instant:

import time

fn main() void {
    zone := time.TimeZone.utc()
    instant := time.DateTime.from_epoch_seconds(1700000000)
    local := instant.in_zone(zone)

    println("offset ${local.offset().total_seconds()} s")
    println("round trip = ${local.to_utc().equals(instant)}")  // true
    println("local date ${local.date().epoch_days()}")
}

Offset and daylight-saving status depend on both the zone and the instant, so both queries take a DateTime:

import time

fn main() void {
    instant := time.DateTime.from_epoch_seconds(1700000000)
    match time.TimeZone.of("Europe/Berlin") {
        Some(z) => {
            println("offset hours = ${z.offset_at(instant).total_hours()}")
            println("dst = ${z.is_dst(instant)}")
        }
        None => println("no tz database entry")
    }
}

Zone lookup and offset queries reach the host time-zone database and suspend. Store absolute events as DateTime; apply a TimeZone only when displaying them or making a calendar decision.

A worked example

Deadlines are the common case: an instant plus a span, compared against the clock.

import time

struct Lease {
    holder   string
    acquired time.DateTime
    ttl      time.Duration
}

fn expires_at(lease &Lease) time.DateTime {
    return lease.acquired.plus(lease.ttl)
}

fn is_expired(lease &Lease, at time.DateTime) bool {
    return expires_at(lease).is_before(at)
}

fn remaining(lease &Lease, at time.DateTime) time.Duration {
    left := expires_at(lease).diff(at)
    return if left.is_negative() { time.Duration.of_micros(0) } else { left }
}

fn main() void {
    now := time.DateTime.now()

    stale := Lease {
        holder:   "worker-3"
        acquired: now.minus(time.Duration.of_minutes(90))
        ttl:      time.Duration.of_hours(1)
    }
    println("expired = ${is_expired(stale, now)}")
    println("remaining = ${remaining(stale, now).total_seconds()}s")

    fresh := Lease { holder: "worker-4", acquired: now, ttl: time.Duration.of_hours(1) }
    println("fresh remaining = ${remaining(fresh, now).total_minutes()}m")

    zone := time.TimeZone.of("America/New_York") ?? time.TimeZone.utc()
    local := expires_at(fresh).in_zone(zone)
    println("lease expires at ${local.hour()}:${local.minute()} local")
}

Waiting

time.sleep(d) suspends the calling task for at least d, then resumes it.

import time

fn poll_twice() int {
    first := time.DateTime.now()
    time.sleep(time.Duration.of_millis(50))
    second := time.DateTime.now()
    return second.diff(first).total_millis()
}

At least: the scheduler resumes a due task on its next pass, so anything already ready goes first. A duration of zero or less resumes without parking at all — which is what makes time.sleep(deadline.minus(elapsed)) safe to write in a retry loop without checking the sign.

A sleeping task is off the ready queue entirely. It costs one entry in a table the scheduler reuses: no task, no frame, no host future, and no allocation once that table has reached the high-water mark of concurrently outstanding waits. That is why taking out a timeout you expect to throw away is a reasonable thing to do on every request.

The two clocks, and which measures what

Call Line Use it for
time.DateTime.now() wall clock naming an instant a human recognizes, storing one, crossing the SQL boundary
time.monotonic_nanos() monotonic measuring an interval — a timeout, a backoff, a latency

They are different in kind, not just in origin. A wall clock can be corrected backwards between two readings — NTP, a manual set, a leap smear — so second.diff(first) over a wall clock can come back negative for two readings taken in order. time.monotonic_nanos() cannot: it only ever goes forwards.

Its absolute value means nothing. The origin is whenever the process first asked, so only differences between two readings are facts. It is the same line the scheduler puts time.sleep’s deadlines on, which is why a deadline computed from it and a duration slept against it agree.

import time

fn timed() int {
    before := time.monotonic_nanos()
    time.sleep(time.Duration.of_millis(5))
    return time.monotonic_nanos() - before
}

time.sleep parks the task, so every function on the path to it inherits the Suspend effect; time.DateTime.now(), time.TimeZone.of and time.monotonic_nanos() read their answer directly and carry none. You do not annotate either — the compiler infers it. See Effects.

Current limits

The installed temporal surface has no parsing, no formatting, no month or year arithmetic, no day-of-week values, no date ranges, and no constructor that resolves a local civil time back into an instant — ZonedDateTime is only ever produced by DateTime.in_zone. TimeZone also has no name() accessor and no fixed-offset form; the zone is an opaque id.

Keep that policy in application code or a host integration until the stdlib grows the API.

Type to search…

↑↓ navigate↵ selectEsc close