Standard library · Time and concurrency

time

The current time, durations, formatting and parsing dates, the monotonic clock, timers and tickers.

import time

The time package reads the clock, turns dates into text and back, does date arithmetic, measures how long code takes and waits. It works with two kinds of value:

•

An instant is an i64 count of seconds since the start of 1970 in UTC, the Unix epoch. Now returns one, and dates are stored, compared and sent as instants.

•

A duration is a Duration, a span with nanosecond precision such as 1h30m, which you can add up, compare and print.

There are also two clocks. The wall clock (Now, NowMillis) tells the date and can jump when the system time is set. The monotonic clock (MonoNanos) only moves forward and is the one to measure spans and deadlines with; timers and tickers use it.

For the Persian and Hijri calendars and for named time zones such as Asia/Tehran, see calendar. For timing parts of a program while you debug it, debug has named timers.

The things people get wrong:

•

Year, FormatDate, Format, FormatISO and Weekday use the machine's local time zone, so the same instant prints differently on a server set to UTC and a laptop in Tehran. Use the ...UTC functions and FormatISOUTC for anything stored or compared.

•

FormatISO has no offset, so the text cannot be read back to the same instant on another machine. Send FormatISOUTC or FormatRFC3339.

•

Days(30) is 30 times 24 hours, not a month. There is no month arithmetic; build the date with FromUTCParts and a month one higher (it rolls 13 over into January).

•

FromUTCParts and FromLocalParts accept any numbers and roll over: 30 February becomes 1 March. The parse functions, by contrast, throw for a day that the month does not have.

•

Timing code with Now. It has whole seconds and follows clock changes; use MonoNanos.

Dates from text, and date arithmetic

Dates usually arrive as text: from JSON, a database or a form. ParseISO reads the ISO 8601 form and returns the instant. Bad input is common, so it is declared throw: catch the error with try: ... catch e: and report or skip the value. Once you have an instant, arithmetic is plain integer arithmetic: AddDuration moves it, and DiffSeconds gives the distance between two instants.

time-guide-expiry.salam
import time
import str

func days_left(expires: i64, today: i64): i64:
    ret time.DiffSeconds(expires, today) / time.SecondsPerDay
end

func main:
    today := time.FromUTCParts(2026, 3, 10, 9, 0, 0)
    signups := [
        "2026-01-15T08:30:00Z", "2026-02-20T18:45:00Z", "2026-03-09T23:10:00Z", "not a date"
    ]
    each s in signups:
        mut p := 0 as i64
        try:
            p = time.ParseISO(s)
        catch e:
            println "skipping \"" + s + "\":", e.message
            continue
        end
        expires := time.AddDuration(p, time.Days(30))
        left := days_left(expires, today)
        if left < 0:
            println time.FormatISOUTC(p), "expired", -left, "days ago"
        else:
            println time.FormatISOUTC(p),
                "ends on",
                time.FormatISOUTC(expires),
                "(" + str.FromInt(left) + " days left)"
        end
    end
end
Output
2026-01-15T08:30:00Z expired 24 days ago
2026-02-20T18:45:00Z ends on 2026-03-22T18:45:00Z (12 days left)
2026-03-09T23:10:00Z ends on 2026-04-08T23:10:00Z (29 days left)
skipping "not a date": expected a digit in the year, found 'n'

The example fixes "today" with FromUTCParts so its output never changes; a real program would use Now(). Adding Days(30) adds exactly 30 times 24 hours. In UTC that is always 30 calendar days, but in a zone with daylight saving the local clock time can move by an hour, so keep stored instants in UTC and convert only for display.

Timeouts from settings

A setting such as timeout = 1m30s is easier to read than a number of milliseconds. ParseDuration understands h, m, s, ms, us and ns, in any combination and with fractions. It throws on text it cannot read, and the error's message says why. Check the value against sensible limits too: a parse that worked is not yet a value that makes sense.

time-guide-timeouts.salam
import time

func read_timeout(name: str, text: str, fallback: time.Duration): time.Duration:
    mut d := fallback
    try:
        d = time.ParseDuration(text)
    catch e:
        println name + ": cannot read",
            "\"" + text + "\" (" + e.message + "), using",
            fallback.ToStr()
        ret fallback
    end
    if d.Less(time.Milliseconds(100)) or time.Minutes(10).Less(d):
        println name + ":", d.ToStr(), "is out of range, using", fallback.ToStr()
        ret fallback
    end
    println name + ":", d.ToStr()
    ret d
end

func main:
    connect := read_timeout("connect", "2.5s", time.Seconds(5))
    request := read_timeout("request", "1m30s", time.Seconds(30))
    retry := read_timeout("retry", "soon", time.Seconds(1))
    idle := read_timeout("idle", "2h", time.Minutes(5))
    worst := connect.Add(request.Mul(3)).Add(retry.Mul(2))
    println "worst case for three tries:", worst.ToStr()
    println "idle in milliseconds:", idle.Millis()
end
Output
connect: 2.5s
request: 1m30s
retry: cannot read "soon" (expected a number, found 's'), using 1s
idle: 2h0m0s is out of range, using 5m0s
worst case for three tries: 4m34.5s
idle in milliseconds: 300000

Durations add, subtract, multiply and compare without any unit conversions, and to_str prints them in the same short form that ParseDuration reads. When a quick default is enough, ParseDurationOr does the parse and the fallback in one call.

When the text is not a date

ParseISO, ParseISONanos, ParseISOIn, ParseHTTPDate, ParseFormat and ParseDuration either return a value or throw an Error; nothing half-read comes back. e.kind tells the cases apart: Syntax for a character that does not fit, such as a slash where a dash belongs or a letter in the year, UnexpectedEnd for text that stops early, and OutOfRange for a field that is too large, such as month 13, hour 25, 30 February or a duration longer than about 292 years. e.offset and e.column point at the spot, and e.code is one of time.syntax, time.unexpected_end, time.empty, time.trailing, time.bad_month, time.bad_day, time.bad_hour, time.bad_minute, time.bad_second, time.bad_offset, time.bad_month_name, time.layout_mismatch, time.bad_unit, time.missing_unit or time.overflow. A layout that ParseFormat does not understand is the caller's mistake and throws InvalidArgument with time.bad_layout. When a default is fine, ParseISOOr and ParseDurationOr never throw; for the others, catch the error and use your default.

The next run of a daily job

An instant is seconds since 1970 in UTC, so the start of its UTC day is t - t % SecondsPerDay, and the time of day is the rest. That is enough to work out when a job that runs every night at 02:30 UTC should run next.

time-guide-schedule.salam
import time

func weekday_name(epoch: i64): str:
    names := ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"]
    ret names[(epoch / time.SecondsPerDay) % 7]
end

func next_run(after: i64, hour: int, minute: int): i64:
    day_start := after - after % time.SecondsPerDay
    mut run := day_start + (hour as i64) * time.SecondsPerHour +
        (minute as i64) * time.SecondsPerMinute
    if run <= after:
        run += time.SecondsPerDay
    end
    ret run
end

func main:
    mut t := time.FromUTCParts(2026, 10, 16, 14, 20, 0)
    println "now:", weekday_name(t), time.FormatISOUTC(t)
    repeat 3:
        t = next_run(t, 2, 30)
        println "backup:", weekday_name(t), time.FormatISOUTC(t)
    end
    println "HTTP form:", time.FormatHTTPDate(t)
end
Output
now: Friday 2026-10-16T14:20:00Z
backup: Saturday 2026-10-17T02:30:00Z
backup: Sunday 2026-10-18T02:30:00Z
backup: Monday 2026-10-19T02:30:00Z
HTTP form: Mon, 19 Oct 2026 02:30:00 GMT

1 January 1970 was a Thursday, which is why the weekday table starts there. Weekday gives the same answer for the machine's local time. FormatHTTPDate is the form HTTP headers such as Last-Modified and Expires need.

Heartbeats, deadlines and waiting for a condition

A Ticker fires at a fixed interval: wait sleeps until the next tick, and if the program comes back late it skips the missed ticks instead of firing them all at once, counting them in dropped. A Timer is a single deadline you check with expired, here an upper limit for the whole loop. WaitUntil checks a condition every poll until it holds or limit runs out, which is the usual way to wait for a server or a file to appear.

time-guide-ticker.salam
import time

func main:
    mut ticker := time.NewTicker(time.Milliseconds(20))
    mut deadline := time.NewTimer(time.Milliseconds(500))
    mut beats := 0
    until beats < 5 and not deadline.Expired():
        ticker.Wait()
        beats++
        println "heartbeat", beats
    end
    ticker.Stop()
    println "deadline passed:", deadline.Expired()
    started := time.MonoNanos()
    ready := time.WaitUntil((): ret time.SinceDuration(started).Millis() >= 30 end, time.Milliseconds(5), time.Seconds(1))
    println "cache warm:", ready
    gave_up := time.WaitUntil((): ret false end, time.Milliseconds(5), time.Milliseconds(20))
    println "server came up:", gave_up
end
Output
heartbeat 1
heartbeat 2
heartbeat 3
heartbeat 4
heartbeat 5
deadline passed: false
cache warm: true
server came up: false

All of these run on the calling thread and block it. To do other work between ticks, call fired in your loop instead of wait; to run something truly in the background, start a thread.

Measuring how long code takes

Take MonoNanos before the work and pass it to SinceDuration after. The monotonic clock only moves forward, so the result is right even if the system clock is changed while the code runs; Now is for dates, not for timing.

time-guide-measure.salam
import time

func fib(n: int): i64:
    if n < 2:
        ret n
    end
    ret fib(n - 1) + fib(n - 2)
end

func main:
    start := time.MonoNanos()
    result := fib(27)
    took := time.SinceDuration(start)
    println "fib(27) =", result
    println "measured something:", not took.IsNegative()
    println "under ten seconds:", took.Less(time.Seconds(10))
    budget := time.Seconds(5)
    if budget.Less(took):
        println "slower than the budget of", budget.ToStr()
    else:
        println "within the budget of", budget.ToStr()
    end
end
Output
fib(27) = 196418
measured something: true
under ten seconds: true
within the budget of 5s

The example prints only comparisons, because the measured time is different on every run. To find the slow part of a larger program, the debug package has named timers that build on the same clock.

Which function for which job

JobUse
The current instantNow
An instant from partsFromUTCParts, or FromLocalParts for local time
Read a date from textParseISO, ParseHTTPDate, ParseFormat
Write a date for machinesFormatISOUTC, FormatRFC3339, FormatHTTPDate
Write a date for peopleFormatDate, FormatTime, Format
Move an instant or measure a gapAddDuration, DiffSeconds, DurationBetween
Time a piece of codeMonoNanos with SinceDuration
Wait or repeatSleep, SleepFor, NewTimer, NewTicker, RepeatEvery, WaitUntil
Jalali or Hijri dates, time zonescalendar

Types

Duration

#
struct Duration

A span of time with nanosecond precision; it may be negative.

NameTypeDescription
nsi64 = 0The span in nanoseconds.
time-Duration.salam
import time

func main throw:
    d := time.Hours(1).Add(time.Minutes(30))
    println d.ToStr(), d.Minutes(), d.Secs()
    println time.FormatDuration(time.Milliseconds(1500)),
        time.FormatDuration(time.Microseconds(250)),
        time.FormatDuration(time.Nanoseconds(42))
    println time.Seconds(90).ToStr(), time.Days(2).Hours(), time.SecondsF(0.25).Millis()
    p := try time.ParseDuration("1h15m30.5s")
    println p.ToStr(), p.Seconds()
    try:
        println time.ParseDuration("ten minutes").ToStr()
    catch e:
        println e.KindName(), e.code, e.offset
    end
    println time.ParseDurationOr("?", time.Seconds(5)).ToStr()
    k := time.Minutes(7)
    println k.Sub(time.Minutes(10)).ToStr(), k.Neg().Abs().ToStr(), k.Neg().IsNegative()
    println k.Mul(3).ToStr(), k.Div(2).ToStr(), time.Hours(1).Ratio(k)
    println k.Cmp(time.Seconds(420)), k.Less(time.Hours(1)), k.Equals(time.Seconds(420))
    t := time.Milliseconds(1750)
    println t.Truncate(time.Seconds(1)).ToStr(), t.Round(time.Seconds(1)).ToStr()
    println t.Nanos(), t.Micros(), t.Millis(), time.ZeroDuration().IsZero(), t.Days() < 0.001
end
Output
1h30m0s 90 5400
1.5s 250us 42ns
1m30s 48 250
1h15m30.5s 4530.5
syntax error time.syntax 0
5s
-3m0s 7m0s true
21m0s 3m30s 8
0 true true
1s 2s
1750000000 1750000 1750 true true

Nanos

#
func Nanos(): i64

Micros

#
func Micros(): i64

Millis

#
func Millis(): i64

Secs

#
func Secs(): i64

Seconds

#
func Seconds(): f64

Minutes

#
func Minutes(): f64

Hours

#
func Hours(): f64

Days

#
func Days(): f64

Add

#
func Add(o: Duration): Duration

Sub

#
func Sub(o: Duration): Duration

Mul

#
func Mul(k: i64): Duration

Div

#
func Div(k: i64): Duration

Ratio

#
func Ratio(o: Duration): i64

Neg

#
func Neg(): Duration

Abs

#
func Abs(): Duration

IsZero

#
func IsZero(): bool

IsNegative

#
func IsNegative(): bool

Cmp

#
func Cmp(o: Duration): int

Less

#
func Less(o: Duration): bool

Equals

#
func Equals(o: Duration): bool

Truncate

#
func Truncate(m: Duration): Duration

Round

#
func Round(m: Duration): Duration

ToStr

#
func ToStr(): str

Writes the span as 1h30m0s; the same as FormatDuration.

The example for this item is shown with the ones above: time-Duration.salam

Timer

#
struct Timer

A one-shot timer: it says whether the span you set has passed.

NameTypeDescription
deadline_nsi64 = 0The end instant on the monotonic clock, in nanoseconds.
activebool = falseWhether the timer is running.
time-Timer.salam
import time

mut count := 0

func main:
    mut timer := time.NewTimer(time.Milliseconds(100))
    println timer.Expired(), timer.Remaining().Millis() > 0
    timer.Wait()
    println timer.Expired(), timer.Remaining().IsZero()
    timer.Reset(time.Seconds(10))
    timer.Stop()
    println timer.Expired(), timer.active
    mut ticker := time.NewTicker(time.Milliseconds(50))
    println ticker.Fired()
    ticker.Wait()
    time.Sleep(120)
    println ticker.Fired(), ticker.dropped >= 1
    ticker.Advance()
    println ticker.Remaining().Millis() <= 100
    ticker.Reset(time.Milliseconds(5))
    ticker.Stop()
    println ticker.Fired()
    time.AfterFunc(time.Milliseconds(10), (): println "after 10 milliseconds" end)
    time.RepeatEvery(time.Milliseconds(5), 2, (): println "tick" end)
    println time.Every(time.Milliseconds(5), (): count++ ret count < 3 end)
    count = 0
    println time.WaitUntil((): count++ ret count >= 3 end, time.Milliseconds(5), time.Seconds(5))
    println time.WaitUntil((): ret false end, time.Milliseconds(5), time.Milliseconds(20))
end
Output
false true
true true
false false
false
true true
true
false
after 10 milliseconds
tick
tick
3
true
false

Expired

#
func Expired(): bool

True when the timer is running and its span has passed.

The example for this item is shown with the ones above: time-Timer.salam

Remaining

#
func Remaining(): Duration

The time left, or zero when it has passed or been stopped.

The example for this item is shown with the ones above: time-Timer.salam

Wait

#
func Wait()

Sleeps until the span is over.

The example for this item is shown with the ones above: time-Timer.salam

Reset

#
func Reset(d: Duration)

Starts the timer again from now, for a new span.

The example for this item is shown with the ones above: time-Timer.salam

Stop

#
func Stop()

Stops the timer; from then on it never expires.

The example for this item is shown with the ones above: time-Timer.salam

Ticker

#
struct Ticker

A ticker: it "ticks" at a fixed interval.

NameTypeDescription
interval_nsi64 = 0The interval between ticks, in nanoseconds.
next_nsi64 = 0The instant of the next tick.
activebool = falseWhether the ticker is running.
droppedi64 = 0How many ticks were missed because the program came back to the ticker late.

The example for this item is shown with the ones above: time-Timer.salam

Fired

#
func Fired(): bool

True when a tick is due, and it moves on to the next one; it does not wait. For loops that have other work to do.

The example for this item is shown with the ones above: time-Timer.salam

Wait

#
func Wait()

Sleeps until the next tick.

The example for this item is shown with the ones above: time-Timer.salam

Advance

#
func Advance()

Moves the deadline on by one tick, counting and skipping the missed ticks so the ticker does not fall behind.

The example for this item is shown with the ones above: time-Timer.salam

Remaining

#
func Remaining(): Duration

The time left until the next tick.

The example for this item is shown with the ones above: time-Timer.salam

Reset

#
func Reset(d: Duration)

Changes the interval and starts again from now.

The example for this item is shown with the ones above: time-Timer.salam

Stop

#
func Stop()

Stops the ticker.

The example for this item is shown with the ones above: time-Timer.salam

DateTime

#
struct DateTime

An instant, as seconds since the Unix epoch, the start of 1 January 1970 in UTC.

NameTypeDescription
epochi64 = 0The seconds since the Unix epoch.
time-Local.salam
import time
import str

func main:
    t := time.FromLocalParts(2024, 3, 20, 9, 30, 0)
    println time.Year(t), time.Month(t), time.Day(t), time.Hour(t), time.Minute(t), time.Second(t)
    println time.Weekday(t), time.YearDay(t)
    println time.FormatDate(t), time.FormatTime(t)
    println time.Format(t)
    println time.FormatISO(t)
    r := time.FormatRFC3339(t)
    offset := time.LocalOffsetMinutesAt(t)
    println str.StartsWith(r, "2024-03-20T09:30:00"), (offset == 0) == str.EndsWith(r, "Z")
    dt := time.FromEpoch(t)
    println time.Epoch(dt) == t, dt.epoch == t
    println time.Epoch(time.NowDateTime()) >= t
end
Output
2024 3 20 9 30 0
3 80
2024-03-20 09:30:00
2024-03-20 09:30:00
2024-03-20T09:30:00
true true
true true
true

Constants and variables

SecondsPerMinute

#
const SecondsPerMinute: i32 = 60

The number of seconds in a minute.

time-UTC.salam
import time

func main throw:
    t := time.FromUTCParts(2024, 3, 20, 14, 5, 9)
    println t, time.FormatISOUTC(t)
    println time.YearUTC(t),
        time.MonthUTC(t),
        time.DayUTC(t),
        time.HourUTC(t),
        time.MinuteUTC(t),
        time.SecondUTC(t)
    println time.FormatHTTPDate(t)
    println try time.ParseHTTPDate("Wed, 20 Mar 2024 14:05:09 GMT") == t
    println try time.ParseISO("2024-03-20T17:35:09+03:30") == t
    println try time.ParseISOIn("2024-03-20 17:35:09.25", 210) == t,
        try time.ParseISONanos("2024-03-20T14:05:09.25Z")
    f := try time.ParseFormat("%d/%m/%Y %H:%M %z", "20/03/2024 14:05 +0000")
    println time.FormatISOUTC(f)
    try:
        println time.ParseISO("2024-02-30")
    catch e:
        println e.KindName(), e.code, e.column, e.message
    end
    println time.ParseISOOr("tomorrow", 0)
    later := time.AddDuration(t, time.Days(10))
    println time.FormatISOUTC(later),
        time.DiffSeconds(later, t),
        time.DurationBetween(later, t).ToStr()
    println time.SecondsPerMinute, time.SecondsPerHour, time.SecondsPerDay
end
Output
1710943509 2024-03-20T14:05:09Z
2024 3 20 14 5 9
Wed, 20 Mar 2024 14:05:09 GMT
true
true
true 1710943509250000000
2024-03-20T14:05:00Z
out of range time.bad_day 9 day 30 is out of range for month 2 of 2024 (1 to 29)
0
2024-03-30T14:05:09Z 864000 240h0m0s
60 3600 86400

SecondsPerHour

#
const SecondsPerHour: i32 = 3600

The number of seconds in an hour.

The example for this item is shown with the ones above: time-UTC.salam

SecondsPerDay

#
const SecondsPerDay: i32 = 86400

The number of seconds in a day.

The example for this item is shown with the ones above: time-UTC.salam

Functions

Nanoseconds

#
func Nanoseconds(n: i64): Duration

A span of n nanoseconds.

The example for this item is shown with the ones above: time-Duration.salam

Microseconds

#
func Microseconds(n: i64): Duration

A span of n microseconds.

The example for this item is shown with the ones above: time-Duration.salam

Milliseconds

#
func Milliseconds(n: i64): Duration

A span of n milliseconds.

The example for this item is shown with the ones above: time-Duration.salam

Seconds

#
func Seconds(n: i64): Duration

A span of n seconds.

The example for this item is shown with the ones above: time-Duration.salam

Minutes

#
func Minutes(n: i64): Duration

A span of n minutes.

The example for this item is shown with the ones above: time-Duration.salam

Hours

#
func Hours(n: i64): Duration

A span of n hours.

The example for this item is shown with the ones above: time-Duration.salam

Days

#
func Days(n: i64): Duration

A span of n days.

The example for this item is shown with the ones above: time-Duration.salam

SecondsF

#
func SecondsF(x: f64): Duration

A span of a fractional number of seconds, such as 0.25 for a quarter second.

The example for this item is shown with the ones above: time-Duration.salam

ZeroDuration

#
func ZeroDuration(): Duration

A span of zero.

The example for this item is shown with the ones above: time-Duration.salam

FormatDuration

#
func FormatDuration(d: Duration): str

Writes the span short and readable: 42ns, 250us, 1.5s, 1m30s or 1h15m30.5s.

The example for this item is shown with the ones above: time-Duration.salam

ParseDuration

#
func ParseDuration(s: str): Throws<Duration>

Reads text such as 1h15m30.5s or -250ms. The units are ns, us, ms, s, m, h and d for days, and every number needs one. Throws Syntax for a character or unit it does not know, UnexpectedEnd for empty text or a number with no unit, and OutOfRange when the span does not fit in 64 bits of nanoseconds.

The example for this item is shown with the ones above: time-Duration.salam

ParseDurationOr

#
func ParseDurationOr(s: str, fallback: Duration): Duration

Like ParseDuration, but returns the default instead of throwing when the text is not valid.

The example for this item is shown with the ones above: time-Duration.salam

SleepFor

#
func SleepFor(d: Duration)

Sleeps for the given span.

time-Now.salam
import time

func main:
    start := time.Now()
    a := time.MonoNanos()
    time.Sleep(20)
    time.SleepFor(time.Milliseconds(10))
    b := time.MonoNanos()
    println time.ElapsedMs(a, b) >= 30.0,
        time.ElapsedUs(a, b) >= 30000.0,
        time.ElapsedSec(a, b) < 5.0
    println time.SinceNanos(a) >= 30000000,
        time.SinceMs(a) >= 30.0,
        time.SinceUs(a) >= 30000.0,
        time.SinceSec(a) < 5.0
    println time.SinceDuration(a).Millis() >= 30
    println time.MonoMillis() > 0, time.MonoMicros() > 0
    println time.Now() >= start, time.Since(start) >= 0, time.Until(start + 60) <= 60
    println time.NowMillis() / 1000 >= start,
        time.NowMicros() / 1000000 >= start,
        time.NowNanos() / 1000000000 >= start
end
Output
true true true
true true true true
true
true true
true true true
true true true

SinceDuration

#
func SinceDuration(start_ns: i64): Duration

The span since an instant taken from MonoNanos.

The example for this item is shown with the ones above: time-Now.salam

DurationBetween

#
func DurationBetween(later: i64, earlier: i64): Duration

The span between two epoch instants.

The example for this item is shown with the ones above: time-UTC.salam

AddDuration

#
func AddDuration(epoch: i64, d: Duration): i64

Adds a span to an instant; any fraction of a second is dropped.

The example for this item is shown with the ones above: time-UTC.salam

NowNanos

#
func NowNanos(): i64

The current instant in nanoseconds since the Unix epoch.

The example for this item is shown with the ones above: time-Now.salam

NowMicros

#
func NowMicros(): i64

The current instant in microseconds since the Unix epoch.

The example for this item is shown with the ones above: time-Now.salam

NowMillis

#
func NowMillis(): i64

The current instant in milliseconds since the Unix epoch.

The example for this item is shown with the ones above: time-Now.salam

ElapsedMs

#
func ElapsedMs(start_ns: i64, end_ns: i64): f64

The gap between two nanosecond clock readings, in milliseconds.

The example for this item is shown with the ones above: time-Now.salam

ElapsedUs

#
func ElapsedUs(start_ns: i64, end_ns: i64): f64

The gap between two nanosecond clock readings, in microseconds.

The example for this item is shown with the ones above: time-Now.salam

ElapsedSec

#
func ElapsedSec(start_ns: i64, end_ns: i64): f64

The gap between two nanosecond clock readings, in seconds.

The example for this item is shown with the ones above: time-Now.salam

MonoNanos

#
func MonoNanos(): i64

The monotonic clock in nanoseconds. It never goes backwards, even if the system clock is changed, so use it for measuring spans. Its value on its own means nothing as a date.

The example for this item is shown with the ones above: time-Now.salam

MonoMicros

#
func MonoMicros(): i64

The monotonic clock in microseconds.

The example for this item is shown with the ones above: time-Now.salam

MonoMillis

#
func MonoMillis(): i64

The monotonic clock in milliseconds.

The example for this item is shown with the ones above: time-Now.salam

SinceNanos

#
func SinceNanos(start_ns: i64): i64

The nanoseconds that have passed since a monotonic clock reading.

The example for this item is shown with the ones above: time-Now.salam

SinceMs

#
func SinceMs(start_ns: i64): f64

The milliseconds, with a fraction, since a monotonic clock reading.

The example for this item is shown with the ones above: time-Now.salam

SinceUs

#
func SinceUs(start_ns: i64): f64

The microseconds, with a fraction, since a monotonic clock reading.

The example for this item is shown with the ones above: time-Now.salam

SinceSec

#
func SinceSec(start_ns: i64): f64

The seconds, with a fraction, since a monotonic clock reading.

The example for this item is shown with the ones above: time-Now.salam

NewTimer

#
func NewTimer(d: Duration): Timer

A timer that expires after the given span.

The example for this item is shown with the ones above: time-Timer.salam

NewTicker

#
func NewTicker(d: Duration): Ticker

A ticker with the given interval; a zero or negative interval makes an inactive ticker.

The example for this item is shown with the ones above: time-Timer.salam

AfterFunc

#
func AfterFunc(d: Duration, fn: func())

Waits for the given span and then runs the function. It happens on the same thread and does not return until the function is done, so it is a sleep followed by a call, not a background timer.

The example for this item is shown with the ones above: time-Timer.salam

Every

#
func Every(d: Duration, fn: func(): bool): i64

Runs the function at a fixed interval for as long as it returns true, and returns how many times it ran.

The example for this item is shown with the ones above: time-Timer.salam

RepeatEvery

#
func RepeatEvery(d: Duration, count: int, fn: func())

Runs the function count times at the given interval.

The example for this item is shown with the ones above: time-Timer.salam

WaitUntil

#
func WaitUntil(fn: func(): bool, poll: Duration, limit: Duration): bool

Checks the condition once every poll until it holds or limit passes, and says whether it held.

The example for this item is shown with the ones above: time-Timer.salam

Now

#
func Now(): i64

The current instant in seconds since the Unix epoch.

The example for this item is shown with the ones above: time-Now.salam

NowDateTime

#
func NowDateTime(): DateTime

The current instant as a DateTime.

The example for this item is shown with the ones above: time-Local.salam

FromEpoch

#
func FromEpoch(seconds: i64): DateTime

A DateTime from a number of epoch seconds.

The example for this item is shown with the ones above: time-Local.salam

Epoch

#
func Epoch(dt: DateTime): i64

The epoch seconds of a DateTime.

The example for this item is shown with the ones above: time-Local.salam

Year

#
func Year(epoch: i64): int

The year of this instant in the machine's local time.

The example for this item is shown with the ones above: time-Local.salam

Month

#
func Month(epoch: i64): int

The month, 1 to 12, of this instant in local time.

The example for this item is shown with the ones above: time-Local.salam

Day

#
func Day(epoch: i64): int

The day of the month of this instant in local time.

The example for this item is shown with the ones above: time-Local.salam

Hour

#
func Hour(epoch: i64): int

The hour, 0 to 23, of this instant in local time.

The example for this item is shown with the ones above: time-Local.salam

Minute

#
func Minute(epoch: i64): int

The minute of this instant in local time.

The example for this item is shown with the ones above: time-Local.salam

Second

#
func Second(epoch: i64): int

The second of this instant in local time.

The example for this item is shown with the ones above: time-Local.salam

YearUTC

#
func YearUTC(epoch: i64): int

The year of this instant in UTC.

The example for this item is shown with the ones above: time-UTC.salam

MonthUTC

#
func MonthUTC(epoch: i64): int

The month, 1 to 12, of this instant in UTC.

The example for this item is shown with the ones above: time-UTC.salam

DayUTC

#
func DayUTC(epoch: i64): int

The day of the month of this instant in UTC.

The example for this item is shown with the ones above: time-UTC.salam

HourUTC

#
func HourUTC(epoch: i64): int

The hour, 0 to 23, of this instant in UTC.

The example for this item is shown with the ones above: time-UTC.salam

MinuteUTC

#
func MinuteUTC(epoch: i64): int

The minute of this instant in UTC.

The example for this item is shown with the ones above: time-UTC.salam

SecondUTC

#
func SecondUTC(epoch: i64): int

The second of this instant in UTC.

The example for this item is shown with the ones above: time-UTC.salam

Weekday

#
func Weekday(epoch: i64): int

The day of the week in local time: zero is Sunday, one Monday, up to six for Saturday.

The example for this item is shown with the ones above: time-Local.salam

YearDay

#
func YearDay(epoch: i64): int

Which day of the year it is, counting from one, in local time.

The example for this item is shown with the ones above: time-Local.salam

FormatDate

#
func FormatDate(epoch: i64): str

The local date as 2024-03-20.

The example for this item is shown with the ones above: time-Local.salam

FormatTime

#
func FormatTime(epoch: i64): str

The local clock time as 09:30:00.

The example for this item is shown with the ones above: time-Local.salam

Format

#
func Format(epoch: i64): str

The local date and time with a space between them.

The example for this item is shown with the ones above: time-Local.salam

FormatISO

#
func FormatISO(epoch: i64): str

The local date and time in ISO 8601 without an offset, such as 2024-03-20T09:30:00.

The example for this item is shown with the ones above: time-Local.salam

FormatHTTPDate

#
func FormatHTTPDate(epoch: i64): str

The date format of HTTP headers, always in UTC: Wed, 20 Mar 2024 14:05:09 GMT.

The example for this item is shown with the ones above: time-UTC.salam

Sleep

#
func Sleep(ms: int)

Holds the calling thread for a number of milliseconds.

The example for this item is shown with the ones above: time-Now.salam

DiffSeconds

#
func DiffSeconds(later: i64, earlier: i64): i64

How many seconds there are from earlier to later.

The example for this item is shown with the ones above: time-UTC.salam

Since

#
func Since(t: i64): i64

How many seconds have passed since that instant.

The example for this item is shown with the ones above: time-Now.salam

Until

#
func Until(t: i64): i64

How many seconds are left until that instant, negative when it is past.

The example for this item is shown with the ones above: time-Now.salam

ParseISO

#
func ParseISO(s: str): Throws<i64>

Reads an ISO 8601 date and time, such as 2024-03-20T17:35:09+03:30 or 2024-03-20, and returns the instant in whole seconds; a fraction is checked and dropped. Without an offset it assumes local time. Throws Syntax or UnexpectedEnd for text in another shape and OutOfRange for a field that does not exist, such as month 13 or 30 February.

The example for this item is shown with the ones above: time-UTC.salam

ParseISONanos

#
func ParseISONanos(s: str): Throws<i64>

Like ParseISO, but keeps the fraction of a second: it returns nanoseconds since the Unix epoch. Also throws OutOfRange for a date before 1677 or after 2262, which do not fit.

The example for this item is shown with the ones above: time-UTC.salam

ParseISOIn

#
func ParseISOIn(s: str, offsetMinutes: int): Throws<i64>

Like ParseISO, but without an offset it assumes offsetMinutes minutes. Throws the same errors.

The example for this item is shown with the ones above: time-UTC.salam

ParseHTTPDate

#
func ParseHTTPDate(s: str): Throws<i64>

Reads the date format of HTTP headers, such as Wed, 09 Jun 2021 10:18:14 GMT, and the two older forms HTTP still allows. The zone must be GMT, UTC or a numeric offset. Throws like ParseISO, and Syntax for an unknown month name.

The example for this item is shown with the ones above: time-UTC.salam

ParseFormat

#
func ParseFormat(pattern: str, s: str): Throws<i64>

Reads text with a pattern. %Y is a four digit year, %y a two digit one, %m the month, %d the day, %H the hour, %M the minute, %S the second, %f the fraction, %b the English month name, %a the day name, which is ignored, %z an offset such as +0330 and %Z a zone name such as UTC. One space in the pattern matches any number of spaces in the text. Throws like ParseISO when the text does not fit the pattern, and InvalidArgument for a directive it does not know.

The example for this item is shown with the ones above: time-UTC.salam

ParseISOOr

#
func ParseISOOr(s: str, fallback: i64): i64

Like ParseISO, but returns the default instead of throwing when the text is not valid.

The example for this item is shown with the ones above: time-UTC.salam

FormatISOUTC

#
func FormatISOUTC(epoch: i64): str

Writes the instant in UTC in ISO 8601, such as 2024-03-20T14:05:09Z.

The example for this item is shown with the ones above: time-UTC.salam

FormatRFC3339

#
func FormatRFC3339(epoch: i64): str

Writes the instant in local time with its offset, such as 2024-03-20T17:35:09+03:30, or Z when the offset is zero.

The example for this item is shown with the ones above: time-Local.salam

LocalOffsetMinutesAt

#
func LocalOffsetMinutesAt(epoch: i64): int

The difference between local time and UTC at that instant, in minutes. With daylight saving it can change over the year.

The example for this item is shown with the ones above: time-Local.salam

FromLocalParts

#
func FromLocalParts(year: int, month: int, day: int, hour: int, minute: int, second: int): i64

Builds an instant from a local year, month, day, hour, minute and second. Values out of range roll over into the next month or year.

The example for this item is shown with the ones above: time-Local.salam

FromUTCParts

#
func FromUTCParts(year: int, month: int, day: int, hour: int, minute: int, second: int): i64

Builds an instant from UTC parts. Values out of range roll over, so month 13 is January of the next year.

The example for this item is shown with the ones above: time-UTC.salam