Core time

@core/time separates monotonic elapsed time from UTC wall-clock time. Many APIs blur these domains, which makes duration measurements vulnerable to clock changes. Moth gives each domain an opaque type.

Choose the explanation level: Time helpers

Time helpers

@core/time separates elapsed time from wall-clock time. Bind it when you need to measure durations or work with UTC timestamps.

Three types of time

  • Duration for elapsed amounts
  • TimeMark for measuring elapsed time and frame deltas
  • Timestamp for real-world UTC instants

These types stay opaque. Pass them to the package functions. Do not construct them with struct syntax.

Measuring elapsed time

Use TimeMark for a monotonic measurement point. Use Duration for the elapsed amount.

@core/time TimeMark, mark_now, duration_between, as_seconds

previous ~= mark_now()

current = mark_now()
delta = duration_between(previous, current)
~previous = current

seconds = as_seconds(delta)

This shape works for frame-delta style code without requiring a scheduler or animation package. Durations also compose directly: duration_add, duration_subtract and duration_scale combine elapsed amounts without converting through seconds.

UTC timestamps

Use Timestamp for real-world UTC instants that may be logged, stored or exchanged with external systems.

@core/time Timestamp, timestamp_from_iso_string, timestamp_from_unix_milliseconds, to_iso_string

parse_created || -> Timestamp, Error!:
    return timestamp_from_iso_string("1970-01-01T00:00:00.000Z")!
;

created = parse_created() catch:
    then timestamp_from_unix_milliseconds(0.0)
;

rendered = to_iso_string(created) catch:
    then "1970-01-01T00:00:00.000Z"
;

io.line(rendered)

timestamp_from_iso_string rejects text outside the accepted ISO format. to_iso_string rejects instants outside its renderable range. Handle both fallible functions with ! or catch.

Timestamps compose too: timestamp_offset moves an instant by a duration and timestamp_difference measures the duration between two instants.

For the full function list, backend behaviour and deferred surfaces, see Core time advanced.

@core/time separates elapsed time from wall-clock time. It belongs to the binding-backed Core package family with no prelude alias, so it requires an explicit dependency clause.

@core/time carries Core origin with ExternalBinding backing. See Package origins and backing for origin and backing rules.

Dependency roots

Bind individual symbols or the whole namespace:

@core/time Duration, TimeMark, mark_now, duration_between, as_seconds

@core/time

previous = time.mark_now()

Opaque types

The package exposes three opaque types. Do not construct them with struct syntax or inspect their fields. Pass them to the package functions.

Type

Purpose

Duration

Signed elapsed amount

TimeMark

Monotonic clock mark for deltas and frame timing

Timestamp

UTC wall-clock instant for logs, storage and system boundaries

All three use the handle ABI. They carry no source-visible fields.

Monotonic clock functions

Function

Parameters

Returns

Error

mark_now()

none

TimeMark

no

elapsed_since(start)

TimeMark

Duration

no

duration_between(start, end)

TimeMark, TimeMark

Duration

no

mark_now() returns the current monotonic mark. elapsed_since(start) returns the duration from start to now. duration_between(start, end) returns the duration from start to end.

Wall-clock timestamp functions

Function

Parameters

Returns

Error

timestamp_now()

none

Timestamp

no

timestamp_from_unix_seconds(seconds)

F64

Timestamp

no

timestamp_from_unix_milliseconds(milliseconds)

F64

Timestamp

no

timestamp_from_iso_string(text)

String

Timestamp, Error!

yes

timestamp_from_iso_string fails on text outside the accepted ISO format, and on accepted text naming an instant outside the renderable window. to_iso_string fails on instants outside that window. Both return through Error!.

@core/time Timestamp, timestamp_from_iso_string, timestamp_from_unix_milliseconds

created = timestamp_from_iso_string("not-a-date") catch:
    then timestamp_from_unix_milliseconds(0.0)
;

Duration construction and helpers

Function

Parameters

Returns

Error

duration_from_seconds(seconds)

F64

Duration

no

duration_from_milliseconds(milliseconds)

F64

Duration

no

as_seconds(duration)

Duration

F64

no

as_milliseconds(duration)

Duration

F64

no

is_negative(duration)

Duration

Bool

no

abs(duration)

Duration

Duration

no

clamp(duration, min, max)

Duration, Duration, Duration

Duration

no

duration_add(left, right)

Duration, Duration

Duration

no

duration_subtract(left, right)

Duration, Duration

Duration

no

duration_scale(duration, factor)

Duration, F64

Duration

no

duration_add(left, right) returns the sum of left and right. duration_subtract(left, right) returns left minus right. duration_scale(duration, factor) returns the result of scaling duration by factor.

Timestamp helpers

Function

Parameters

Returns

Error

unix_seconds(timestamp)

Timestamp

F64

no

unix_milliseconds(timestamp)

Timestamp

F64

no

to_iso_string(timestamp)

Timestamp

String, Error!

yes

timestamp_offset(timestamp, duration)

Timestamp, Duration

Timestamp

no

timestamp_difference(start, end)

Timestamp, Timestamp

Duration

no

timestamp_offset(timestamp, duration) returns the instant duration away from timestamp. timestamp_difference(start, end) returns the duration from start to end, mirroring duration_between.

Semantic contract

Timestamp counts milliseconds from the Unix epoch, 1970-01-01T00:00:00Z, and always denotes a UTC instant. Duration is a signed millisecond quantity. TimeMark is a point on a monotonic clock whose origin is unspecified and unobservable. Marks are meaningful only as arguments to elapsed_since and duration_between. A mark never decreases within one program run, and both functions return a non-negative duration when the earlier mark is passed first.

timestamp_from_iso_string accepts exactly one text format:

  • a calendar date YYYY-MM-DD
  • the separator T
  • a time of day HH:MM:SS
  • an optional fractional second written as . followed by one to nine digits
  • a mandatory UTC designator, either Z or a numeric offset +HH:MM or -HH:MM

Text that does not match returns builtin error code 310 through Error!. This rejects a missing designator, a lowercase t or z, surrounding whitespace, a date-only string and any other calendar or locale convention.

Field values are validated: month 1 to 12, a day that exists in that month of that year, hour 0 to 23, minute and second 0 to 59, and the same hour and minute ranges in a numeric offset. An out-of-range field returns code 310 instead of rolling over into the next day or month. Leap seconds are not accepted.

Fractional seconds resolve to milliseconds. Digits beyond the third are truncated toward zero, never rounded.

to_iso_string renders the same format with a Z designator and exactly three fractional digits. Rendering requires an instant between 0000-01-01T00:00:00.000Z and 9999-12-31T23:59:59.999Z, the window the four-digit year spelling can express, so every rendered string parses back through timestamp_from_iso_string. An instant outside that window returns builtin error code 311 through Error!, and the window is tested before truncation, so a fractional instant just outside it is rejected rather than pulled in. A fractional millisecond inside the window is truncated toward zero before rendering. Parsing applies the same window after the offset is converted, so accepted text naming an instant outside it also returns code 311.

Duration arithmetic is addition, subtraction and multiplication of millisecond quantities. It is exact while the operands and the result stay within the whole numbers an F64 represents exactly, a range far wider than the renderable window; beyond that it rounds like any other F64 arithmetic, so adding one millisecond to a duration of 1e16 milliseconds returns the same duration. Because the arithmetic functions return opaque values, a result that leaves the finite F64 range is not rejected where the arithmetic happens: it is rejected with builtin error code 304 when the duration is read as an F64 by as_seconds or as_milliseconds, at the shared external F64 boundary.

clamp(duration, min, max) is the composition min(max(duration, min), max), so when min exceeds max the upper bound wins and the result is max.

A duration whose quantity has already left the finite range is still a valid opaque Duration, and whether it is outside the range when it is read depends on what is applied to it. clamp can bring an infinite quantity back between its bounds, and that clamped result is an ordinary finite duration. A quantity that is not a number, which repeated arithmetic can reach by scaling an overflowed duration by zero, propagates through abs and clamp instead, and no bound recovers it. is_negative answers from the same comparison with zero as it does for any duration, so it is false for a quantity that is not a number and true only for a quantity below zero. The composition rule and the reversed-bound result above hold whenever the operands hold a number. Any quantity still outside the finite range when an F64 accessor reads it is rejected with builtin error code 304.

Every F64 reaching this package is already finite, because NaN and the infinities are never valid Moth F64 values, so the package validates no argument of its own. The four F64-returning accessors as_seconds, as_milliseconds, unix_seconds and unix_milliseconds are checked by that shared boundary.

Duration, TimeMark and Timestamp support no equality, no ordering and no use as map keys. Compare durations through as_milliseconds and timestamps through unix_milliseconds.

Every failure this package itself detects is observable in Moth as a returned Error!. The one failure it delegates is a non-finite F64 result at the shared external boundary. That Moth-owned check is a fatal integrity guard, not implicit built-in failure: it halts unless a declared builtin Error! contract returns it. Safety-catch eligibility does not turn this guard into a recoverable failure. No function in this package throws a host error of its own.

Access and return contracts

All parameters use shared access. No function requires mutable access. All return values stay fresh. timestamp_from_iso_string returns through Error! on text outside the accepted ISO format and on accepted text whose offset-adjusted instant leaves the renderable window. to_iso_string returns through Error! when the instant lies outside that window. Every other function declares no typed error slot; a non-finite F64 at that shared boundary still halts unless a declared builtin Error! contract returns it.

Unsupported source forms

  • Direct symbol-path clauses such as @core/time/mark_now face rejection. Use direct selections or a namespace clause.
  • Named arguments are not supported. Binding-backed calls are positional-only.
  • Do not construct Duration, TimeMark or Timestamp with struct syntax.
  • Do not inspect opaque type fields directly.
  • The package does not expose receiver methods.

API boundaries

Calendar date types, time zones, local-time conversion, locale-aware formatting, timers, sleep, intervals and animation callbacks are outside the @core/time API. Animation-frame integration belongs in a web-specific package.

Related concepts