docs

您正在閱讀 v0.1.2 的文件。Nabi 0.1.2 已停止支援。 最新版本:v0.1.3 →

本頁尚未翻譯,以下為英文原文。

#3.3. time:: - time

本頁內容

Time is split across two modules by what it needs. core::time holds Duration and Instant: the monotonic clock already runs in core (task timers, 2.18), so both work on every target and need no use (0.2). std::time holds the clocks that need the operating system: the wall clock SystemTime, the boot clock BootTime and UNIX_EPOCH. It also holds the civil calendar: Date, Time, DateTime, Period, Offset, TimeZone and Zoned (3.3.6 to 3.3.8), since time zones come from the operating system's tz database. Each type has one path (0.1.6); std::time does not re-export the core types. The monotonic clock, the wall clock and time elapsed since boot are kept clearly separate, so the clock that fits the measurement can be chosen.

#3.3.1. The four-type model

The overall picture:

TypeModuleMeaningUsed for
Instantcore::timeMonotonic clockDuration measurement / timeouts
Durationcore::timeTime difference (i64 nanoseconds)Difference between two times / sleep argument
SystemTimestd::timeWall clock (UTC, NTP-adjustable)File mtime / display to users
BootTimestd::timeTime since boot (including suspend)Mobile / laptop apps

The internal representation of Duration is i64 ns. The u128 that Rust adopted was judged excessive; i64 already covers about ±292 years, which is ample for practical use.

One rule for every clock. The span between two readings of any clock is the exact signed Duration: a.duration_since(b) is negative when b is later, never an error, none or zero. elapsed() measures on a monotonic clock, so a step of the wall clock cannot make it negative. This is Go's rule (time.Sub, time.Since).

#3.3.2. Instant - monotonic clock

nabi
// core::time
struct Instant { /* opaque (CLOCK_MONOTONIC / QueryPerformanceCounter) */ }

impl Instant {
    fn now() -> Instant;

    fn elapsed(self) -> Duration;
    const fn duration_since(self, earlier: Instant) -> Duration;   // self - earlier, signed

    // arithmetic: returns none on failure (avoids Rust's silent saturating-on-overflow)
    const fn checked_add(self, dur: Duration) -> Instant | none;
    const fn checked_sub(self, dur: Duration) -> Instant | none;
}

// ordinary arithmetic; on overflow, panic with overflow checks on, saturate with them off (3.3.5)
impl Add<Duration> for Instant { type Output = Instant; ... }
impl Sub<Instant> for Instant { type Output = Duration; ... }
impl Sub<Duration> for Instant { type Output = Instant; ... }

The key properties of Instant: it never goes backward, so it is unaffected by NTP adjustment. It has no absolute time meaning of its own (its reference is process start), so it cannot be serialized. For the same reason, comparisons across processes are meaningless; it is meaningful only within the same process.

duration_since returns a negative Duration when earlier is later. To clamp a span, compare it: d.max(Duration::ZERO).

#Example

The most common pattern is to take a starting point and get the elapsed time with elapsed.

nabi
let start = Instant::now();
heavy_computation();
let elapsed = start.elapsed();          // Duration
log(f"computation took {elapsed:?}");

#3.3.3. SystemTime - wall clock

SystemTime is i64 nanoseconds relative to UNIX_EPOCH, so its range is about ±292 years on every target. 32-bit targets read the clock through 64-bit time interfaces (time64), so there is no 2038 limit.

SystemTime behaves quite differently. Time may go backward through NTP adjustment or user changes, and since it is an absolute time relative to UNIX_EPOCH it can be serialized. It can therefore be compared meaningfully across processes.

duration_since is the signed difference of the wall readings: a later earlier gives a negative Duration, not an error. unix_secs rounds down, so SystemTime::from_unix(t.unix_secs(), n) gives t back for its sub-second part n, also before the epoch.

Monotonic reading. SystemTime::now() also reads the monotonic clock (Instant's). elapsed() measures on that reading, so a step of the wall clock between now() and elapsed() does not change the result. + / - / checked_* with a Duration move both readings. A SystemTime that did not come from now() (from_unix, UNIX_EPOCH, Metadata::modified) has none, and its elapsed() is SystemTime::now().duration_since(self). Comparison, equality and hashing use the wall reading only.

#Example

Converting to a unix timestamp and reading a file's mtime:

nabi
use std::time::SystemTime;

let now = SystemTime::now();
log(f"unix timestamp: {now.unix_secs()}");

// file mtime
let meta = try fs::metadata("data.txt");
let mtime: SystemTime = try meta.modified();
log(f"file age: {mtime.elapsed():?}");     // negative if the mtime is in the future

#3.3.4. BootTime - time since boot (including suspend)

nabi
// std::time
struct BootTime { /* CLOCK_BOOTTIME (Linux) / CLOCK_MONOTONIC = mach_continuous_time (macOS) */ }

impl BootTime {
    fn now() -> BootTime;
    fn elapsed(self) -> Duration;
    const fn duration_since(self, earlier: BootTime) -> Duration;   // self - earlier, signed
}

As with Instant, duration_since is negative when earlier is later. BootTime and Instant differ in their behavior across suspend. Instant, like Linux CLOCK_MONOTONIC, stops during suspend, whereas BootTime follows CLOCK_BOOTTIME and keeps advancing during suspend.

This difference is decisive when a mobile or laptop app must measure "real elapsed time (including suspend)". Rust still has no stable API for this as of 2026; Nabi exposes it on the surface early.

#3.3.5. Duration

a.min(b) on two durations is Ord::min.

Display writes a single unit fitting the magnitude: s if the absolute value is at least 1 second, ms if at least 1 ms, µs if at least 1 µs, and ns otherwise. The integer part divided by that unit is followed by the remainder as a fraction; trailing zeros are removed, and if the remainder is 0 no decimal point is written. Negative values are prefixed with -.

nabi
Duration::ms(1234);      // "1.234s"
Duration::ms(5);         // "5ms"
Duration::ns(1500);      // "1.5µs"
Duration::ns(-20);       // "-20ns"

All time types implement Clone / Copy / PartialEq / Eq / PartialOrd / Ord / Hash / Debug. Duration also implements Default (zero).

#Duration arithmetic policy

Arithmetic on Duration / SystemTime / Instant / BootTime (including duration_since and from_unix) panics on overflow when overflow checks are on and saturates when they are off (-C overflow-checks, refs-lang 9.1.2). The f64 forms (Duration::secs_f64, f64 * Duration) follow the same rule: a non-finite or out-of-range result panics with checks on and saturates (NaN to zero) with them off. Division by zero always panics. The checked_* / saturating_* variants of Duration choose explicitly.

nabi
impl Duration {
    const fn checked_add(self, rhs: Duration) -> Duration | none;
    const fn checked_sub(self, rhs: Duration) -> Duration | none;
    const fn checked_mul(self, factor: i64) -> Duration | none;
    const fn checked_div(self, divisor: i64) -> Duration | none;

    const fn saturating_add(self, rhs: Duration) -> Duration;
    const fn saturating_sub(self, rhs: Duration) -> Duration;
    const fn saturating_mul(self, factor: i64) -> Duration;
}

#3.3.6. Calendar dates and times

The calendar types have no time zone: they are what a wall calendar and a wall clock show. All are Copy values, ordered by time, with Hash; Display / FromStr are ISO 8601 (3.3.8).

TypeHoldsDisplay
Dateyear, month, day (proleptic Gregorian)2024-02-29
Timehour, minute, second, nanosecond09:05:00.25
DateTimea Date and a Time2024-03-10T02:30:00
Periodyears, months, days, each kept apartP1Y2M10D
WeekdayMonday .. SundayMonday

Range and calendar. A Date is a day of the proleptic Gregorian calendar between MIN_YEAR and MAX_YEAR; year 0 is 1 BC, as ISO 8601 counts. Day counts use Howard Hinnant's civil algorithms, exact over the whole range. unix_days counts from 1970-01-01, which is day 0.

Wrong fields throw, overflowing arithmetic panics. A constructor that gets fields which are not a date or time (Date::new(2023, 2, 29), Time::new(24, 0, 0)) throws a ValueError naming the field and its range: day 29 is out of range for 2023-02 (1..=28). Arithmetic that leaves the range (Date::MAX.add_days(1)) panics, as Duration does; the checked_* forms return none instead.

Months clamp. add_months and add_years keep the day of the month when the new month has it, and otherwise take the new month's last day: 2024-01-31 plus one month is 2024-02-29, and 2024-02-29 plus one year is 2025-02-28. Each call clamps on its own, so two add_months(1) from January 31 end on March 29, while add_months(2) ends on March 31. Date + Period adds years and months together (clamping once), then the days. This is the rule of java.time and Temporal.

until is the calendar span from self to later: whole years, then whole months, then days, all with the sign of the span, chosen so that d + d.until(e) == e for any two dates. days_since is the plain difference in days.

ISO weeks. iso_week is ISO 8601's week numbering: weeks start on Monday, and week 1 holds the year's first Thursday, so 2021-01-03 is in week 53 of 2020 and 2024-12-30 in week 1 of 2025.

#Example

nabi
use std::time::{Date, DateTime, Period, Time};

let d = try Date::new(2024, 1, 31);
println(f"{d} {d.weekday()} day {d.ordinal()}");
println(f"{d.add_months(1)} {d.add_months(1).add_months(1)} {d.add_months(2)}");
println(f"{try Date::new(2024, 2, 29).add_years(1)}");

let end = try Date::new(2025, 3, 1);
let p = d.until(end);
println(f"{p} {d + p} {end.days_since(d)} days");
println(f"{try Date::new(2021, 1, 3).iso_week():?}");

let t = try (try Time::new(9, 5, 0)).with_nanosecond(250000000);
let dt = d.and_time(t);
println(f"{dt} {dt + Duration::hours(15)} {dt + Period::of_days(1)}");
try { println(f"{try Date::new(2023, 2, 29)}"); } catch e { println(f"{e}"); }
2024-01-31 Wednesday day 31
2024-02-29 2024-03-29 2024-03-31
2025-02-28
P1Y1M1D 2025-03-01 395 days
(2020, 53)
2024-01-31T09:05:00.250 2024-02-01T00:05:00.250 2024-02-01T09:05:00.250
day 29 is out of range for 2023-02 (1..=28)

#3.3.7. Offsets, time zones and Zoned

An Offset is a fixed difference from UTC. A TimeZone gives the offset at each instant. A Zoned is one instant together with the zone it is shown in.

Where zones come from. TimeZone::get reads a zone of the tz database (IANA) as a TZif file (RFC 8536, versions 1 to 4) from $TZDIR when it is set, else from the first of /usr/share/zoneinfo, /usr/lib/zoneinfo, /usr/share/lib/zoneinfo and /etc/zoneinfo that exists. Past the last transition in the file, the POSIX TZ rule in its footer gives the offsets, so dates far in the future follow the current rules. UTC, the other UTC names (Etc/UTC, GMT, Zulu, ...) and offsets (+09:00) work with no database. Any other name without a database throws, and the error says that the system has none: Windows and the browser have no tz database, and WASI programs see one only when the host grants the directory. from_tzif reads a TZif file the program brings itself (for example with include_bytes!), which works on every target. from_posix takes a POSIX TZ rule (EST5EDT,M3.2.0,M11.1.0; its offsets are west positive, as POSIX writes them).

The local zone. TimeZone::local() reads $TZ first: a database name (Asia/Seoul), a path to a TZif file (/usr/share/zoneinfo/Asia/Seoul, a leading : is dropped) or a POSIX rule. Without $TZ it reads /etc/localtime, named after /etc/timezone when that file names a zone, else localtime. When none of these gives a zone, it is UTC. It reads files on each call, so a program keeps the result.

Gaps and overlaps. Where the clocks move forward (a gap), some local times never happen; where they move back (an overlap), some happen twice. in_zone_with takes the choice, as java.time and Temporal do:

DisambiguationIn an overlap (01:30 shown twice)In a gap (02:30 skipped, 02:00 to 03:00)
Compatiblethe earlier instantmoved forward by the gap: 03:30
Earlierthe earlier instantread with the offset after the gap: 01:30
Laterthe later instantread with the offset before the gap: 03:30
Rejectthrows ValueErrorthrows ValueError

in_zone is in_zone_with(.., Disambiguation::Compatible), which is what most systems do and cannot fail. The Reject error names the zone, the two offsets and what to pass instead: 2024-03-10T02:30:00 does not exist in America/New_York: the clocks skip it (-05:00 to -04:00); pass Disambiguation::Earlier or Disambiguation::Later. add_days, add_months, add_years and + Period on a Zoned move the civil date, keep the time of day, and resolve the result as Compatible; + Duration adds exact time.

is_dst_at and Zoned::is_dst report the zone data's daylight saving flag. Most zones mark summer time; a zone with negative DST marks its winter time instead (IST-1GMT0,M10.5.0,M3.5.0/1, the rule of Europe/Dublin in most tz builds).

Equality. Two Zoned values are equal, ordered and hashed by their instant only: 2024-01-01T09:00:00+09:00 equals 2024-01-01T00:00:00Z. Two TimeZones are equal when they have the same name.

#Example

nabi
use std::time::{DateTime, Disambiguation, Offset, TimeZone};

let ny = try TimeZone::get("America/New_York");
let dt = try DateTime::new(2024, 3, 10, 2, 30, 0);
println(f"{dt.in_zone(ny)}");
println(f"{try dt.in_zone_with(ny, Disambiguation::Earlier)}");
try { println(f"{try dt.in_zone_with(ny, Disambiguation::Reject)}"); } catch e { println(f"{e}"); }

let before = (try DateTime::new(2024, 3, 9, 12, 0, 0)).in_zone(ny);
println(f"{before.add_days(1)} {before + Duration::hours(24)}");
println(f"{before.abbreviation()} {before.add_days(1).abbreviation()}");

let seoul = before.in_zone(TimeZone::fixed(try Offset::new(9, 0)));
println(f"{seoul} {seoul == before}");
2024-03-10T03:30:00-04:00
2024-03-10T01:30:00-05:00
2024-03-10T02:30:00 does not exist in America/New_York: the clocks skip it (-05:00 to -04:00); pass Disambiguation::Earlier or Disambiguation::Later
2024-03-10T12:00:00-04:00 2024-03-10T13:00:00-04:00
EST EDT
2024-03-10T02:00:00+09:00 true

#3.3.8. Text: ISO 8601, RFC 3339 and patterns

Display writes, and FromStr (str::parse) reads, the standard forms:

TypeDisplayFromStr also reads
Date2024-02-29, -000044-03-15, +012345-01-01
Time09:05:00, 09:05:00.25009:05, a fraction of 1 to 9 digits, , for .
DateTime2024-03-10T02:30:00t or a space for T
Offset+09:00, -03:30, +05:30:15Z, +0900, +09
Zoned2024-03-10T03:30:00-04:00, ...ZRFC 9557's [America/New_York] suffix
SystemTime2023-11-14T22:13:20Z (UTC)any offset
PeriodP1Y2M10D, P0D, P-1M-3D(no FromStr)

A year outside 0..=9999 has a sign and six digits, as ISO 8601's expanded form. The fraction is written in 3, 6 or 9 digits, the fewest that hold it, and left out when it is zero. A Zoned with a zero offset writes Z; its Debug adds the zone name in brackets (2024-03-10T03:30:00-04:00[America/New_York]). Reading a Zoned with a bracketed zone loads that zone; the offset must agree with it, or the error names both (with no offset, the local time resolves as Compatible). Without a bracket, the zone is the fixed offset. A DateTime text with an offset is an error that says to parse a Zoned or a SystemTime.

Errors name the place. A parse error is a ParseError whose message names the byte offset and what belongs there: cannot parse "2024/02/03": expected `-` after the year at byte 4, found `/` , cannot parse "2024-13-01": month 13 is out of range (1..=12) at byte 5. position() is the same offset.

Patterns. format(pattern) on Date, Time, DateTime and Zoned writes strftime-style directives; parse_with(text, pattern) reads the same directives back. Names are English (the C locale).

DirectiveMeaningDirectiveMeaning
%Yyear, at least 4 digits%Hhour 00..23
%Ccentury (%Y / 100)%Ihour 01..12
%yyear % 100, 2 digits%k / %l%H / %I padded with a space
%mmonth 01..12%Mminute 00..59
%dday 01..31%Ssecond 00..59
%eday, padded with a space%fnanoseconds, 9 digits; %3f %6f %9f
%jday of the year 001..366%p / %PAM / PM, am / pm
%a / %AMon / Monday%z / %:zoffset +0900 / +09:00
%b / %h / %BJan / Jan / January%Zabbreviation (KST), or the offset
%u / %wweekday 1..7 from Monday / 0..6 from Sunday%sunix seconds
%G / %g / %VISO week year / its last 2 digits / ISO week%F%Y-%m-%d
%U / %Wweek of the year from Sunday / Monday%T%H:%M:%S
%D / %x%m/%d/%y%R%H:%M
%c%a %b %e %H:%M:%S %Y%r%I:%M:%S %p
%n / %tnewline / tab%%%

A flag after % changes the padding: - none (%-d is 5), _ spaces, 0 zeros. A pattern is program text, so an unknown directive, or one the value lacks (%H on a Date, %z on a DateTime), panics with a message that says what to write.

parse_with reads numbers of up to the directive's width (%Y up to 4 digits, or 6 after a sign), names in any case and in full or three letters, and lets one space in the pattern match any run of whitespace. Missing time fields are zero; a Date needs a year (%Y, or %y with 69..99 as 19xx), and a month and day or a %j. A weekday that does not match the date is an error. %Z reads UTC, GMT, UT, Z or a zone name such as Europe/Paris; abbreviations such as EST are ambiguous and rejected with a pointer to %z. Zoned::parse_with needs an offset, a zone or %s. %C, %g, %G, %V, %U and %W are write-only.

Mail and HTTP. Zoned::to_rfc2822 and Zoned::parse_rfc2822 are the date of RFC 5322 mail (Sat, 14 Nov 2026 09:30:00 +0900); parsing takes the weekday and the seconds as optional and the obsolete zone names (GMT, EST, PDT, ...). SystemTime::to_http_date is RFC 9110's IMF-fixdate (Sun, 06 Nov 1994 08:49:37 GMT), and parse_http_date also reads the two obsolete forms a server must accept (Sunday, 06-Nov-94 08:49:37 GMT, Sun Nov 6 08:49:37 1994).

nabi
impl Date {
    const fn format(self, pattern: str) -> str;
    fn parse_with(text: str, pattern: str) throws (ParseError) -> Date;
}
// the same on Time, DateTime and Zoned
impl Zoned {
    const fn to_rfc2822(self) -> str;
    fn parse_rfc2822(text: str) throws (ParseError) -> Zoned;
}

#Example

nabi
use std::time::{Date, DateTime, SystemTime, Zoned};

let t = SystemTime::from_unix(1700000000, 250000000);
println(f"{t} {t.to_http_date()}");
let z = try "2023-11-15T07:13:20+09:00".parse::<Zoned>();
println(f"{z} {z.to_utc()} {z.format("%A %-d %B %Y, %I:%M %p %:z")}");

let dt = try DateTime::parse_with("10/03/2024 2:05 PM", "%d/%m/%Y %I:%M %p");
println(f"{dt} {dt.format("%F %T")} {dt.date().format("%G-W%V-%u")}");
try { println(f"{try "2024-02-30".parse::<Date>()}"); } catch e { println(f"{e}"); }
println(f"{try Zoned::parse_rfc2822("Sat, 14 Nov 2026 09:30:00 +0900")}");
2023-11-14T22:13:20.250Z Tue, 14 Nov 2023 22:13:20 GMT
2023-11-15T07:13:20+09:00 2023-11-14T22:13:20Z Wednesday 15 November 2023, 07:13 AM +09:00
2024-03-10T14:05:00 2024-03-10 14:05:00 2024-W10-7
cannot parse "2024-02-30": day 30 is out of range for 2024-02 (1..=29) at byte 8
2026-11-14T09:30:00+09:00

#3.3.9. Policy - no TAI / leap second support

SystemTime is strictly UTC and does not handle leap seconds (taking into account that the Linux kernel itself is ambiguous here). The calendar types follow it: every day has 86400 seconds, Time has no second 60, and parsing 23:59:60 is an error that says so. Cases that need TAI (atomic time) or exact leap second handling belong to separate packages.

UseRecommendation
Ordinary apps (timestamps / measurement)core::time, std::time
Simulation / precise astronomyA separate chrono-like package
Finance / exact leap secondsA separate package

#3.3.10. impl / target

Per-platform implementation mapping:

Itemlinuxmacoswindowswasi
InstantCLOCK_MONOTONICCLOCK_UPTIME_RAWQueryPerformanceCounterwasi clock
SystemTimeCLOCK_REALTIMECLOCK_REALTIMEGetSystemTimePreciseAsFileTimewasi
BootTimeCLOCK_BOOTTIMECLOCK_MONOTONIC (mach_continuous_time, includes sleep)QueryPerformanceCounter (~ Instant)(no suspend)
TimeZone::get$TZDIR, /usr/share/zoneinfo/usr/share/zoneinfonone: UTC and offsets onlythe host's files when it grants them, else none
TimeZone::local$TZ, /etc/localtime$TZ, /etc/localtimea POSIX rule in $TZ, else UTC$TZ when passed in, else UTC

#3.3.11. Policy summary

The chapter's key decisions are five. First, Instant / SystemTime / Duration are separated, distinguishing monotonic time from wall-clock time semantically; Duration and Instant live in core::time, the OS clocks in std::time. Second, every span is the exact signed Duration, and elapsed() runs on a monotonic clock. Third, BootTime, which Rust's std does not cover, is exposed separately so that elapsed time since boot, including suspend, can be read directly. Fourth, TAI and leap seconds are split out into separate packages outside this module. Fifth, the calendar is in std, as in Python, Go and Java: civil types with no zone (Date, Time, DateTime) are kept apart from an instant in a zone (Zoned), a local time that a zone skips or repeats is resolved by an explicit Disambiguation, and the text forms are the standard ones (RFC 3339 for Display, strftime patterns, RFC 2822 and HTTP dates).

Found a mistake? Edit this page on GitHub. Last updated