Appearance
std/time
From the spec
This page is spec/std/time.md, the specification the compiler and the backends are written from. It is rebuilt from the spec with every deploy (how).
Instants, durations, dates and times, and time zones, in Temporal's design (the TC39 proposal), small. It is written in Weft (core/crates/weft-check/src/std/time.weft): a project that imports it gets it as a module of its own (id std/time), so the VM and the JS backend run the same code and give the same results. Only the time-zone rules and the clock come from the host (std/$time). Unlike the I/O modules, user code (std/sandbox) may import it.
weft
import { plainDate, zonedDateTime, plainDateTime, duration, now } from "std/time"
let due = plainDate.add(try plainDate.from("2024-01-31"), { months: 1 }) // 2024-02-29
let meet = plainDateTime.toZoned(plainDateTime.of(2024, 3, 10, 2, 30), "America/New_York")
zonedDateTime.toString(meet) // 2024-03-10T03:30:00-04:00[America/New_York]
duration.toString(zonedDateTime.until(meet, zonedDateTime.add(meet, { days: 1 }))) // PT24HValues
Every value is data (a record: it compares with ==, converts to json and crosses to the client and the database); the functions are in namespaces named after the types.
| type | fields |
|---|---|
Instant | epochMs (an integer), nanos (the nanoseconds within it, 0–999,999) |
Duration | years months weeks days hours minutes seconds milliseconds microseconds nanoseconds, each optional (0); integers of one sign |
PlainDate | year month day (ISO 8601, proleptic Gregorian) |
PlainTime | hour minute second millisecond microsecond nanosecond |
PlainDateTime | the two above together |
ZonedDateTime | epochMs nanos timeZone offsetMs and the wall clock's fields |
- A
ZonedDateTimeis its instant and its zone; the other fields follow from them, so one passes where anInstant, aPlainDateor aPlainDateTimeis expected (records project,language.md, Types). Durations this module gives have every field. - The range is Temporal's: ±100,000,000 days from 1970 (a panic past it). Exact times are kept as integer milliseconds and nanoseconds, exact in a double throughout.
Unitis"years" … "nanoseconds";Disambiguation"compatible" | "earlier" | "later" | "reject";Overflow"constrain" | "reject".
Errors and panics
Text and zone names come from outside; numbers are the program's:
- Reading text fails with
TimeError = TimeError { input: string, message: string }: every namespace'sfrom(text)(instant.from(text): Instant ! TimeError,duration.from, …), andparseZone(name): string ! TimeError, which gives a zone name as the database spells it (parseZone("europe/paris")is"Europe/Paris"): check a zone from outside with it once. - Everything else panics (
RangeError): a value past the range, fields that aren't integers (or a duration's of two signs), a date that doesn't exist given by its fields (plainDate.of(2023, 2, 29)), an unknown zone name,"reject"when the result would be constrained or is ambiguous (it asserts that it isn't), and arithmetic that needs a zone or a starting date (below).
Functions
| namespace | |
|---|---|
instant | fromEpochMs(ms), fromEpochNs(digits), epochNs(i) (decimal digits), from(text), toString(i, timeZone?), add(i, d), subtract, until(a, b, largest = "seconds"), since, compare(a, b), toZoned(i, timeZone) |
duration | of(d) (checked, every field), from(text), toString(d), negated, abs, sign, add(a, b), subtract, total(d, unit), compare(a, b) |
plainDate | of(y, m, d), from, toString, add(d, by, overflow = "constrain"), subtract, until(a, b, largest = "days"), since, compare, dayOfWeek (1 Monday … 7), dayOfYear, weekOfYear, yearOfWeek (ISO weeks), daysInMonth, daysInYear, inLeapYear, toDateTime(d, time?), toZoned(d, timeZone) (its first instant) |
plainTime | of(h = 0, …), from, toString, add(t, by) (wraps at midnight; days and larger ignored), subtract, until(a, b, largest = "hours"), since, compare |
plainDateTime | of(y, m, d, h = 0, …), from, toString, add(x, by, overflow), subtract, until(a, b, largest = "days"), since, compare, toZoned(x, timeZone, disambiguation = "compatible"), toDate, toTime |
zonedDateTime | from(text, disambiguation = "compatible"), toString, add(x, by, overflow), subtract, until(a, b, largest = "hours"), since, compare, withTimeZone, startOfDay, hoursInDay, toInstant, toPlainDateTime, toPlainDate, toPlainTime |
now(): Instant, nowIn(timeZone?): ZonedDateTime, today(timeZone?): PlainDate and localTimeZone(): string are effectful (pure units can't call them): the clock is the host's (a test host's fake one), the zone TZ, else the system's, else UTC. The module also exports the host's sleep(ms) and timers (setTimeout, setInterval, clearTimeout, clearInterval; std.md, std/time).
elapsed(): number (effectful) is milliseconds on a monotonic clock that advances inside a turn, as performance.now(), for timing work: let t = elapsed(); work(); log(elapsed() - t) (now() is the turn's instant and doesn't move within it). Its zero is unspecified (about when the program started); only differences mean anything. It reads the engine's clock (the VM's, performance.now() on the web; a corpus case's engineClock), and a test host's fake clock in weft test.
Arithmetic
As Temporal's, operation for operation (the corpus's expected output is computed by Temporal's reference implementation, scripts/time-cases.mjs):
- Dates add years and months first (the day constrained to the month, or a panic with
"reject": Jan 31 + 1 month is Feb 29 in 2024), then weeks and days; hours and smaller count as whole days. A date-time adds its time first and carries whole days into the date. - Instants add hours and smaller only; days and larger need a zone (a panic).
- Zoned date-times add years, months, weeks and days on the wall clock (a gap or fold then resolved
compatible), then hours and smaller as exact time:{ days: 1 }across a daylight-saving change is 23 or 25 hours,{ hours: 24 }is 24. - Differences (
until(a, b), fromatob) are balanced up tolargest. Years and months count only while adding them toadoesn't passb, comparing the day before it is constrained (Temporal's ISODateSurpasses: Jan 31 until Feb 29 isP29D, notP1M).since(a, b)isuntil(a, b)negated. A zoned difference in days or more takes whole days on the wall clock and the rest as exact time, both in one zone. - Durations add, subtract, compare and total without a starting date only when they have no years, months or weeks (days are 24 hours there); a sum is balanced up to the larger of the two largest units. There is no rounding (
smallestUnit,roundingMode) yet.
Time zones
- A zone is an IANA name, matched without regard to case and kept as the database spells it (a link keeps its own name:
Asia/Calcuttastays itself),UTC, or a fixed offset±HH:MM. - A wall-clock time the zone skips (a gap) or repeats (a fold):
compatibletakes the later instant in a gap and the earlier in a fold;earlier,later;rejectpanics (inzonedDateTime.from, text read: it fails withTimeError). A date whose midnight is in a gap starts when the gap ends (startOfDay,toZoned). - The tz data: the VM bundles the IANA database in the binary (
jiff'sjiff-tzdb), so a server, a desktop app and a sandbox answer the same on any machine; the JS backend uses the engine's (Intl, ICU's copy of the database). A rule the two copies date differently would differ until both update; the corpus uses settled history only.
Text
ISO 8601 / RFC 9557, as Temporal reads and writes it:
- dates
2024-02-29,+010000-01-01,-000001-12-31(not-000000); timesHH,HH:MM,HH:MM:SSwith a fraction of up to nine digits (.or,),:60read as:59;T,tor a space between;Z; offsets±HH,±HHMM,±HH:MM[:SS[.f]]; annotations[Area/City],[!…],[u-ca=iso8601](another calendar fails; other keys are ignored unless critical). Basic formats without separators are not read. - Plain types refuse
Z;instant.fromneedsZor an offset;zonedDateTime.fromneeds the zone annotation, and an offset given must be the zone's at that time (to the minute unless it has seconds), and the zone must be known; else it fails withTimeError. Text it doesn't read fails the same way. - Written: fractions without trailing zeros, seconds always; years outside 0–9999 as
±YYYYYY;zonedDateTime.toStringandinstant.toString(i, zone)round the offset to minutes (-04:56for New York's local mean time;offsetMskeeps the seconds). - Durations:
[±]P[nY][nM][nW][nD][T[nH][nM][n[.f]S]], a fraction on the last time unit only (PT1.5His 1 hour 30 minutes); written with milliseconds and smaller as the seconds' fraction ({ milliseconds: 1500 }isPT1.5S),PT0Sfor zero.
Decided here
- Records in namespaces (
plainDate.add(d, …)) rather than methods: Weft has no methods on records, and one name can't be both an imported type and a value. A module function per namespace is also callable with UFCS where its name is unique. - The module is Weft compiled with the program rather than host code twice, so the backends agree by construction; the host gives only zone offsets and the clock.
- Bundled tz data on the VM (deterministic everywhere, no system files needed in containers or on devices); the engine's on the web.
- Temporal's semantics where they are defined, checked against its reference implementation rather than V8's (Node 24's
--harmony-temporalgets negative date differences,totalin days andyearOfWeekwrong). - Only the ISO calendar; no rounding options,
with, month-day or year-month types yet. - Only reading text fails (
TimeError); the rest panics,"reject"included (an assertion). Zone names from outside go throughparseZoneonce, so the functions taking a zone stay infallible.