Documentation/Reference

Dates, times, durations and clocks

On this page

These types and functions are in the standard prelude. No import, native date library or process timezone setting is required. Constructors and parsers validate their inputs. Checked failures are DateTimeError with Kind, Message, InputByteOffset (-1 if inapplicable) and optional UnderlyingOSCode. Catch them in TRY blocks or declare them with FAILS DateTimeError in functions.

day = NewDate(2024, Month.January, 31)
PRINT FormatDate(AddMonths(day, 1, DateOverflow.Constrain))
instant = ParseInstant("2024-01-01T01:00:00.000000007+01:00")
PRINT FormatInstant(instant)
PRINT FormatDuration(Nanoseconds(-1))
Use Types and operations
Calendar values Date, TimeOfDay, LocalDateTime, YearMonth, MonthDay, IsoWeekDate. Use NewDate, NewTime, NewLocalDateTime, Parts, WeekOfYear, AddDays, AddMonths, AddYears and the typed Parse/Format functions.
A point on the Unix timeline Instant, with InstantFromUnixSeconds(seconds, nanosecond), scaled constructors, UnixSeconds, NanosecondFraction, CompareInstant, ElapsedBetween and AddDuration. The civil range is years −999,999,999 through 999,999,999, with astronomical year zero and the proleptic Gregorian calendar.
A local time with a stated offset UtcOffset, OffsetTime, OffsetDateTime. Use NewUtcOffset, AtOffset, ToInstant, OffsetOf, LocalPart and WithOffsetSameInstant. A local datetime by itself is not an instant.
Exact elapsed time Duration, with Nanoseconds, Microseconds, Milliseconds, Seconds, checked Minutes/Hours, NewDuration, arithmetic, ParseDuration and FormatDuration.
Calendar arithmetic Period stores months and days. NewPeriod, AddPeriod, CalendarBetween and DateTimeAmount apply calendar rules first and exact duration second. DateOverflow.Reject is the default; .Constrain clamps a missing day to the end of the month. A calendar day in a zone can differ from 24 elapsed hours.
Timezone rules TimeZone, ZonedDateTime, ZoneDatabase. Use UtcZone, FixedOffsetZone, NewTransitionZone, LoadTimeZoneFile, LoadTimeZoneBytes, ZoneDatabaseFromEntries, FindTimeZone, AtZone, MapLocal and ResolveLocal.
Clocks and deadlines NowInstant(), NewSystemClock, NewTestClock, NowMonotonic, ElapsedBetween, CompareMonotonic, DeadlineAfter, Remaining, IsExpired.

Duration is one exact value with a signed INTEGER floor-seconds component and a normalized nanosecond fraction in 0..999999999. For example, Nanoseconds(-1) has DurationSeconds of -1 and NanosecondFraction of 999999999. Constructors through Seconds accept every INTEGER; arithmetic can fail if the resulting seconds do not fit. DurationNanoseconds, DurationMicroseconds and DurationMilliseconds check the range of the requested total; the latter two also check precision unless a rounding mode is supplied. RoundDuration currently requires its quantum to fit signed nanoseconds.

The old NanosecondCount field is removed. Use the checked total accessors, or keep the wide Duration. For a sign test, Compare(delay, Seconds(0)) returns CompareResult.Less, .Equal or .Greater without narrowing the duration. SELECT CASE AFTER rejects positive delays/deadlines outside the scheduler’s signed nanosecond range with DateTimeError before registering any waits; nonpositive delays are ready immediately. TCP, TLS and resolver timeouts retain IoError (22 for negative input, 75 for range overflow). Terminal and GTK timeout handling also checks narrowing. Sleep still takes integer milliseconds. Rebuild .blib files with package ABI v12.

Zones and local time

Load an explicit TZif file, for example LoadTimeZoneFile("America/Toronto", "/usr/share/zoneinfo/America/Toronto"), or give ZoneDatabaseFromEntries a list of ZoneDataEntry {Id=..., Data=...} values. The database owns an immutable snapshot of those entries. There is no implicit zone lookup from the environment or mutable global database. MapLocal reports unique, ambiguous, or nonexistent mappings. ResolveLocal takes explicit LocalResolveOptions for overlap/gap policy and defaults to rejecting both. Explicitly select how a calendar addition through a clock change is resolved.

TZif v1–v4 and supported POSIX footer rules are read with bounds and consistency checks. Unspecified local time types, missing rules and leap-aware TZif data fail explicitly. Fixed offsets compare by signed seconds. Named TimeZone values compare by ID and cached rules digest; SameZoneRules compares digests. ZonedDateTime equality includes the instant, zone ID and rules digest. SameInstant compares only timeline position. Offset datetime equality includes the local value and offset. Periods, mixed amounts and offset/zoned values do not have an implicit ordering. Use an explicit comparison for the intended axis.

Clocks

NowInstant() reads wall time. NewSystemClock() defaults to Linux MonotonicBasis.ActiveTime (does not count suspend); BootTime includes it. Elapsed measurements use ElapsedBetween(NowMonotonic(clock), laterSample). Every Clock is an owned resource. Samples and deadlines are independent values, tied to the creating clock’s domain. Comparing or using them with a different domain fails with ClockDomainMismatch. DeadlineAfter rejects negative durations; Remaining returns zero after expiry.

NewTestClock(initialWall) creates a deterministic clock. AdvanceTestClock borrows it BYREF, advances wall and monotonic time together, and commits neither change if either would overflow. AdjustTestWallClock changes only wall time. Test clocks drive these clock and deadline operations; scheduler waits still use the scheduler’s system monotonic clock.

Text and storage

Strict ISO-style parsers use ASCII digits and explicit offsets where required. They do not guess missing fields or normalize invalid dates or leap seconds. ParseOptions can opt into ASCII whitespace trimming and bounded input. FormatOptions offers fixed fraction widths and checked rounding. Compiled patterns support numeric year/month/day/hour/minute/second/fraction and numeric offset fields with ASCII literals. See the calendar example .

ParseRfc3339 preserves the timestamp’s offset designation (including an unknown local offset). ParseRfc9557 resolves supported named zone and ISO calendar annotations using a supplied snapshot and offset conflict policy. It retains supported noncritical annotations, but has no lossless re-emitter. ParseHttpDate and FormatHttpDate handle IMF-fixdate; obsolete HTTP date grammars are outside this profile.

Date, clock-of-day, local/offset datetime, instant, UTC offset, offset time, partial-date, ISO-week and duration values have default text codecs for typed JSON. Period uses a versioned object with exact month/day strings so mixed signs round-trip. A JsonCodec profile or a field converter can choose another representation. InstantToStorageJSON, PeriodToStorageJSON and ZonedToStorageJSON provide explicit versioned envelopes. Restoring a named zoned value requires a snapshot with the matching rules digest. SQLite uses ordinary typed cells: choose SqlText(FormatDate(day)) or a documented epoch unit with SqlInteger, and decode explicitly. No date type is inferred from SQL text or a numeric cell.

Locale-sensitive text, automatic OS timezone/database discovery, scheduler injection of test clocks, richer database mappings, and native TOML/binary date transport are separate checklist work .

From the BASIL documentation. View source ↗

Find your way around BASIL

Type to search the manual.