Esc

Time

moduleextensionSource
  • macOS: Everything works on macOS
  • Linux: Everything works on Linux
  • Windows: Everything works on Windows
  • Wasm: Everything works on Wasm
·since 0.36.1

#import "Extensions/Time";

Exact instants, civil values, explicit zones and calendar-aware spans.

Types never mix by accident: a Timestamp is an exact instant, a Date_Time is a wall-clock reading with no zone, and a Zoned is an instant read in an explicit Time_Zone. Every fallible procedure returns a Time_Error; error.kind == .NONE means success.

Civil values and calendar arithmetic:

Example↗
day, error := date(2024, 1, 31);
assert(error.kind == .NONE);
next_month, _ := add(day, Span.{ months = 1 });
assert(next_month.month == 2 && next_month.day == 29); // clamped to the month's end
assert(weekday(next_month) == .THURSDAY);

Instants, zones and daylight-saving gaps:

Example↗
zone, error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(error.kind == .NONE);
defer time_zone_free(*zone);

// 02:30 does not exist on 2024-03-10; the default policy moves it forward.
wall := Date_Time.{ .{ 2024, 3, 10 }, .{ 2, 30, 0, 0 } };
z, _ := to_zoned(wall, zone);
assert(z.offset.seconds == -14400);
_, rejected := to_zoned(wall, zone, .REJECT);
assert(rejected.kind == .GAP);

Text:

Example↗
instant, _ := parse(Timestamp, "2024-03-10T07:30:00Z");
builder: String_Builder;
defer free_buffers(*builder);
format(*builder, instant, "%d %b %Y");
text := builder_to_string(*builder);
defer free(text);
assert(text == "10 Mar 2024");

Procedures#

Civil#

datesince 0.36.1Source
(year: s64, month: s64, day: s64) -> (Date, Time_Error)

Validates Gregorian components without clamping.

d, error := date(2024, 2, 29);
assert(error.kind == .NONE && d.day == 29);
_, bad := date(2023, 2, 29);
assert(bad.kind == .INVALID_VALUE);
↗
time_of_daysince 0.36.1Source
(hour: s64, minute: s64, second: s64, nanosecond: s64 = 0) -> (Time_Of_Day, Time_Error)

Validates a clock reading; leap seconds are rejected.

t, error := time_of_day(23, 59, 59, 1);
assert(error.kind == .NONE && t.nanosecond == 1);
_, bad := time_of_day(24, 0, 0);
assert(bad.kind == .INVALID_VALUE);
(year: s64, month: s64) -> (s64, Time_Error)

Returns the Gregorian month length after validating year and month.

n, error := days_in_month(2024, 2);
assert(error.kind == .NONE && n == 29);
↗
iso_weeksince 0.36.1Source
(value: Date) -> (s64, s64)

Returns ISO week-year and week number; week one contains January 4.

year, week := iso_week(Date.{ 2021, 1, 1 });
assert(year == 2020 && week == 53);
↗
add6 overloadssince 0.36.1Source
(value: Date, amount: Span, overflow := Overflow.CONSTRAIN) -> (Date, Time_Error)
(value: Date_Time, amount: Span, overflow := Overflow.CONSTRAIN) -> (Date_Time, Time_Error)
(value: Time_Of_Day, amount: Span) -> (Time_Of_Day, Time_Error)
(value: Timestamp, amount: Span) -> (Timestamp, Time_Error)
(value: Zoned, amount: Span, overflow := Overflow.CONSTRAIN, disambiguation := Disambiguation.COMPATIBLE) -> (Zoned, Time_Error)

Applies years/months with month-end policy, then weeks/days; clock units fail.

d, error := add(Date.{ 2024, 1, 31 }, Span.{ months = 1 });
assert(error.kind == .NONE && d.month == 2 && d.day == 29);
_, rejected := add(Date.{ 2024, 1, 31 }, Span.{ months = 1 }, .REJECT);
assert(rejected.kind == .INVALID_VALUE);
↗

Instants#

offsetsince 0.36.1Source
(seconds: s64) -> (Offset, Time_Error)

Validates seconds east of UTC, including historical second offsets.

o, error := offset(-14400);
assert(error.kind == .NONE && o.seconds == -14400);
_, bad := offset(100000);
assert(bad.kind != .NONE);
↗

Spans#

span_checksince 0.36.1Source
(value: Span) -> (Span, Time_Error)

Validates the single-sign invariant without balancing units.

ok, error := span_check(.{ months = 1, days = 2 });
assert(error.kind == .NONE && ok.days == 2);
_, mixed := span_check(.{ years = 1, days = -1 });
assert(mixed.kind == .INVALID_VALUE);
↗
until4 overloadssince 0.36.1Source
(a: Date, b: Date, largest := Unit.DAY, smallest := Unit.NANOSECOND, rounding := Rounding.TRUNC, increment: s64 = 1) -> (Span, Time_Error)
(a: Date_Time, b: Date_Time, largest := Unit.DAY, smallest := Unit.NANOSECOND, rounding := Rounding.TRUNC, increment: s64 = 1) -> (Span, Time_Error)
(a: Timestamp, b: Timestamp, largest := Unit.SECOND, smallest := Unit.NANOSECOND, rounding := Rounding.TRUNC, increment: s64 = 1) -> (Span, Time_Error)
(a: Zoned, b: Zoned, largest := Unit.DAY, smallest := Unit.NANOSECOND, rounding := Rounding.TRUNC, increment: s64 = 1, disambiguation := Disambiguation.COMPATIBLE) -> (Span, Time_Error)

Measures b minus a; validates units, positive increments and range.

a := Date.{ 2024, 1, 1 };
b := Date.{ 2024, 3, 1 };
days, _ := until(a, b);
assert(days.days == 60);
months, _ := until(a, b, largest = .MONTH);
assert(months.months == 2);
↗
since4 overloadssince 0.36.1Source
(a: Date, b: Date, largest := Unit.DAY, smallest := Unit.NANOSECOND, rounding := Rounding.TRUNC, increment: s64 = 1) -> (Span, Time_Error)
(a: Date_Time, b: Date_Time, largest := Unit.DAY, smallest := Unit.NANOSECOND, rounding := Rounding.TRUNC, increment: s64 = 1) -> (Span, Time_Error)
(a: Timestamp, b: Timestamp, largest := Unit.SECOND, smallest := Unit.NANOSECOND, rounding := Rounding.TRUNC, increment: s64 = 1) -> (Span, Time_Error)
(a: Zoned, b: Zoned, largest := Unit.DAY, smallest := Unit.NANOSECOND, rounding := Rounding.TRUNC, increment: s64 = 1, disambiguation := Disambiguation.COMPATIBLE) -> (Span, Time_Error)

Measures a minus b; validates units, positive increments and range.

span, error := since(Date.{ 2024, 3, 1 }, Date.{ 2024, 1, 1 });
assert(error.kind == .NONE && span.days == 60);
↗
span_round3 overloadssince 0.36.1Source
(value: Span, smallest: Unit, largest: Unit, rounding := Rounding.HALF_EXPAND, increment: s64 = 1) -> (Span, Time_Error)
(value: Span, smallest: Unit, largest: Unit, rounding := Rounding.HALF_EXPAND, increment: s64 = 1, relative: Date) -> (Span, Time_Error)
(value: Span, smallest: Unit, largest: Unit, rounding := Rounding.HALF_EXPAND, increment: s64 = 1, relative: Zoned) -> (Span, Time_Error)

Rounds to a positive increment, then balances; calendar rounding needs a relative value.

span, error := span_round(.{ hours = 1, minutes = 40 }, .HOUR, .HOUR);
assert(error.kind == .NONE && span.hours == 2);
↗
span_negatesince 0.36.1Source
(value: Span) -> Span

Reverses every field of a validated span.

s := span_negate(.{ months = 1, days = 2 });
assert(s.months == -1 && s.days == -2);
↗
span_abssince 0.36.1Source
(value: Span) -> Span

Returns a nonnegative span; span_check rejects signed minima.

s := span_abs(.{ hours = -3 });
assert(s.hours == 3);
↗

Zone load#

(name: string, bytes: [] u8, options: Time_Options = .{}) -> (Time_Zone, Time_Error)

Copies validated TZif v1-v4 rules and POSIX footer within bounded storage.

bytes := u8.[
    0x54, 0x5a, 0x69, 0x66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 4,
    0, 0, 0x1c, 0x20, 0, 0, 0x4d, 0x59, 0x54, 0, // one type: +02:00 "MYT"
];
zone, error := time_zone_from_tzif("Example/Zone", bytes);
assert(error.kind == .NONE);
defer time_zone_free(*zone);
instant, _ := timestamp_from_seconds(0);
assert(offset_at(zone, instant).seconds == 7200);
↗

Zoned#

to_timestampsince 0.36.1Source
(zone: Time_Zone, wall: Date_Time, disambiguation := Disambiguation.COMPATIBLE) -> (Timestamp, Time_Error)

Resolves gaps/folds using the requested policy and checks UTC range.

zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
gap := Date_Time.{ .{ 2024, 3, 10 }, .{ 2, 30, 0, 0 } };
instant, error := to_timestamp(zone, gap);
assert(error.kind == .NONE && instant.seconds == 1710055800);
_, rejected := to_timestamp(zone, gap, .REJECT);
assert(rejected.kind == .GAP);
↗
transitionssince 0.36.1Source
(zone: Time_Zone, instant: Timestamp, reverse := false) -> Time_Transitions

Starts a borrowed cursor strictly after instant (strictly before when reverse).

zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
start, _ := timestamp_from_seconds(1704067200);
cursor := transitions(zone, start);
change, found, error := next(*cursor);
assert(error.kind == .NONE && found && change.after.seconds == -14400);
↗
nextsince 0.36.1Source

Advances a transition cursor; false with no error means the range is exhausted.

zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
start, _ := timestamp_from_seconds(1704067200);
cursor := transitions(zone, start);
spring, _, _ := next(*cursor);
autumn, _, _ := next(*cursor);
assert(spring.after.seconds == -14400 && autumn.after.seconds == -18000);
↗
to_zonedsince 0.36.1Source
(wall: Date_Time, zone: Time_Zone, disambiguation := Disambiguation.COMPATIBLE) -> (Zoned, Time_Error)

Resolves civil time and borrows the explicit zone.

zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
fold := Date_Time.{ .{ 2024, 11, 3 }, .{ 1, 30, 0, 0 } };
first, _ := to_zoned(fold, zone, .EARLIER);
second, _ := to_zoned(fold, zone, .LATER);
assert(first.offset.seconds == -14400 && second.offset.seconds == -18000);
↗

Ordering#

Text#

parsesince 0.36.1Source
($T: Type, text: string, options: Time_Options = .{}) -> (T, Time_Error)

Reads the type's ISO text; Zoned rejects conflicting offsets and accepts bare zone annotations.

instant, error := parse(Timestamp, "2024-03-10T07:30:00Z");
assert(error.kind == .NONE && instant.seconds == 1710055800);
_, bad := parse(Date, "2024/02-29");
assert(bad.kind == .SYNTAX && bad.offset == 4);
↗
format2 overloadssince 0.36.1Source
(builder: *Builder, value: $T/ .[Date, Time_Of_Day, Date_Time, Timestamp, Signed_Duration, Offset, Time_Zone, Zoned], pattern: string, options: Time_Options = .{}) -> Time_Error

Uses String_Builder. Appends canonical ISO text, trims fractional zeros and uses UTC Z for timestamps.

instant, _ := timestamp_from_seconds(1710055800);
builder: String_Builder;
defer free_buffers(*builder);
error := format(*builder, instant);
assert(error.kind == .NONE);
text := builder_to_string(*builder);
defer free(text);
assert(text == "2024-03-10T07:30:00Z");
↗

Pattern#

parse_formatsince 0.36.1Source
($T: Type, pattern: string, text: string, options: Time_Options = .{}) -> (T, Time_Error)

Reads the documented English directives; missing or conflicting required fields fail.

wall, error := parse_format(Date_Time, "%Y-%m-%d %H:%M", "2024-03-10 02:30");
assert(error.kind == .NONE && wall.date.day == 10 && wall.time.minute == 30);
_, missing := parse_format(Date, "%m-%d", "03-10");
assert(missing.kind != .NONE);
↗

Interop#

Uses Json_Writer. Custom Json field encoder; canonical ISO strings use Json's writer limits.

#import "Extensions/Json";
T :: #import "Extensions/Time";

Event :: struct {
    day: Date; @json(with=time_json)
    time_json_encode :: T.time_json_encode;
    time_json_decode :: T.time_json_decode;
}

main :: () {
    event, error := from_json(Event, "{\"day\":\"2024-02-29\"}");
    assert(error.kind == .NONE && event.day.day == 29);
    text := to_json(event);
    defer free(text);
    assert(text == "{\"day\":\"2024-02-29\"}");
}

Uses Json_Reader. Custom Json field decoder; parse errors become Json INVALID_VALUE and output stays unchanged.

#import "Extensions/Json";
T :: #import "Extensions/Time";

Event :: struct {
    day: Date; @json(with=time_json)
    time_json_encode :: T.time_json_encode;
    time_json_decode :: T.time_json_decode;
}

main :: () {
    _, error := from_json(Event, "{\"day\":\"2024-02-30\"}");
    assert(error.kind == .INVALID_VALUE);
}

Types#

Datestructsince 0.36.1Source

A Gregorian date in years -9999..9999; construct with date(2024, 3, 10).

Date :: struct {
    year: s16 = 1970;
    month: s8 = 1;
    day: s8 = 1;
}
day := Date.{ 2024, 3, 10 };
assert(day.month == 3);
assert(Date.{}.year == 1970); // the default is 1970-01-01
↗
Time_Of_Daystructsince 0.36.1Source

A clock reading without a zone.

Time_Of_Day :: struct {
    hour: s8;
    minute: s8;
    second: s8;
    nanosecond: s32;
}
t, error := time_of_day(2, 30, 0);
assert(error.kind == .NONE && t.hour == 2 && t.minute == 30);
Date_Timestructsince 0.36.1Source

A wall-clock value, not an instant.

Date_Time :: struct {
    date: Date;
    time: Time_Of_Day;
}
wall, error := date_time(2024, 3, 10, 2, 30, 0);
assert(error.kind == .NONE && wall.date.day == 10 && wall.time.hour == 2);
↗
Timestampstructsince 0.36.1Source

Unix seconds and a signed subsecond remainder. The remainder is in -999999999..999999999 and has the seconds' sign when seconds != 0.

Timestamp :: struct {
    seconds: s64;
    nanoseconds: s32;
}
instant, error := timestamp_from_millis(1500);
assert(error.kind == .NONE && instant.seconds == 1 && instant.nanoseconds == 500000000);
↗
Signed_Durationstructsince 0.36.1Source

Exact elapsed time, with the same remainder invariant as Timestamp.

Signed_Duration :: struct {
    seconds: s64;
    nanoseconds: s32;
}
d, error := signed_duration(1, 5);
assert(error.kind == .NONE && d.seconds == 1 && d.nanoseconds == 5);
↗
Offsetstructsince 0.36.1Source

Seconds east of UTC, within +/-25:59:59.

Offset :: struct {
    seconds: s32;
}
o, error := offset(19800);
assert(error.kind == .NONE && o.seconds == 19800);
↗
Time_Zonestructsince 0.36.1Source

An immutable zone handle. RULES handles own one reference. Assignment borrows; time_zone_retain creates another owner. Release each owner once with time_zone_free; a Zoned borrows its zone.

Time_Zone :: struct {
    kind: Time_Zone_Kind;
    offset: Offset;
    rules: *void;
}
zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
assert(zone.kind == .RULES);
↗
Spanstructsince 0.36.1Source

Separate calendar and clock units, all zero or sharing one sign. Raw field assignment does not validate: use span_check before passing caller-built values to arithmetic.

Span :: struct {
    years: s32;
    months: s32;
    weeks: s32;
    days: s32;
    hours: s64;
    minutes: s64;
    seconds: s64;
    milliseconds: s64;
    microseconds: s64;
    nanoseconds: s64;
}
span, error := span_check(.{ months = 1, days = 2 });
assert(error.kind == .NONE && span.months == 1 && span.days == 2);
↗
Unitenumsince 0.36.1Source

Units ordered from finest to coarsest.

Unit :: enum u8 {
    NANOSECOND;
    MICROSECOND;
    MILLISECOND;
    SECOND;
    MINUTE;
    HOUR;
    DAY;
    WEEK;
    MONTH;
    YEAR;
}
span, _ := span_round(.{ hours = 1, minutes = 40 }, .HOUR, .HOUR);
assert(span.hours == 2);
↗
Weekdayenumsince 0.36.1Source

ISO weekday numbering; e.g. weekday(value) returns MONDAY for 2024-03-11.

Weekday :: enum u8 {
    MONDAY :: 1;
    TUESDAY;
    WEDNESDAY;
    THURSDAY;
    FRIDAY;
    SATURDAY;
    SUNDAY;
}
assert(weekday(Date.{ 2024, 3, 11 }) == .MONDAY);
assert(cast(int) Weekday.SUNDAY == 7);
↗
Roundingenumsince 0.36.1Source

Temporal rounding modes; e.g. .HALF_EVEN sends equal ties to an even multiple.

Rounding :: enum u8 {
    HALF_EXPAND;
    TRUNC;
    FLOOR;
    CEIL;
    EXPAND;
    HALF_TRUNC;
    HALF_EVEN;
    HALF_FLOOR;
    HALF_CEIL;
}
half_up, _ := span_round(.{ seconds = 2, milliseconds = 500 }, .SECOND, .SECOND, .HALF_EXPAND);
half_even, _ := span_round(.{ seconds = 2, milliseconds = 500 }, .SECOND, .SECOND, .HALF_EVEN);
assert(half_up.seconds == 3 && half_even.seconds == 2);
↗
Disambiguationenumsince 0.36.1Source

Resolves skipped/repeated civil times; e.g. .REJECT fails for either ambiguity. COMPATIBLE chooses later in a gap and earlier in a fold.

Disambiguation :: enum u8 {
    COMPATIBLE;
    EARLIER;
    LATER;
    REJECT;
}
zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
gap := Date_Time.{ .{ 2024, 3, 10 }, .{ 2, 30, 0, 0 } };
earlier, _ := to_timestamp(zone, gap, .EARLIER);
later, _ := to_timestamp(zone, gap, .LATER);
assert(later.seconds - earlier.seconds == 3600);
_, rejected := to_timestamp(zone, gap, .REJECT);
assert(rejected.kind == .GAP);
↗
Overflowenumsince 0.36.1Source

Month-end handling; e.g. January 31 plus one month constrains to February's last day.

Overflow :: enum u8 {
    CONSTRAIN;
    REJECT;
}
clamped, _ := add(Date.{ 2024, 1, 31 }, Span.{ months = 1 }, .CONSTRAIN);
assert(clamped.day == 29);
_, rejected := add(Date.{ 2024, 1, 31 }, Span.{ months = 1 }, .REJECT);
assert(rejected.kind != .NONE);
↗
Time_Error_Kindenumsince 0.36.1Source

Failure classification; e.g. error.kind == .NONE means success.

Time_Error_Kind :: enum u8 {
    NONE;
    INVALID_VALUE;
    OUT_OF_RANGE;
    OVERFLOW;
    SYNTAX;
    LIMIT;
    GAP;
    FOLD;
    OFFSET_CONFLICT;
    RELATIVE_REQUIRED;
    IO;
    NOT_FOUND;
    UNSUPPORTED;
}
_, error := date(2024, 13, 1);
assert(error.kind == .INVALID_VALUE);
_, parse_error := parse(Date, "nope");
assert(parse_error.kind == .SYNTAX);
↗
Time_Errorstructsince 0.36.1Source

Static message and zero-based parse byte offset (-1 for other errors). No error owns memory. Failed results must not be used.

Time_Error :: struct {
    kind: Time_Error_Kind;
    message: string;
    offset: s64 = -1;
}
_, error := parse(Date, "2024/02-29");
assert(error.kind == .SYNTAX && error.offset == 4);
_, invalid := date(2023, 2, 29);
assert(invalid.offset == -1); // only parse errors carry an offset
↗
Time_Optionsstructsince 0.36.1Source

Bounds on text, TZif data and rule counts. Each public parser checks these before copying or allocating input-derived storage.

Time_Options :: struct {
    max_text: s64 = 4096;
    max_tzif_bytes: s64 = 16 * 1024 * 1024;
    max_transitions: s64 = 1000000;
    max_types: s64 = 256;
    max_abbreviation_bytes: s64 = 65536;
}
options := Time_Options.{ max_text = 8 };
_, error := parse(Timestamp, "2024-03-10T07:30:00Z", options);
assert(error.kind == .LIMIT);
↗
Time_Transitionstructsince 0.36.1Source

One offset change. Abbreviation slices borrow the iterator's zone owner.

Time_Transition :: struct {
    timestamp: Timestamp;
    before: Offset;
    after: Offset;
    abbreviation_before: string;
    abbreviation_after: string;
}
zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
start, _ := timestamp_from_seconds(1704067200);
cursor := transitions(zone, start);
change, _, _ := next(*cursor);
assert(change.after.seconds - change.before.seconds == 3600);
assert(change.abbreviation_after == "EDT");
↗
Time_Transitionsstructsince 0.36.1Source

A constant-space cursor borrowing a zone.

Time_Transitions :: struct {
    zone: Time_Zone;
    cursor: Timestamp;
    reverse: bool;
    exhausted: bool;
}
zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
start, _ := timestamp_from_seconds(1704067200);
cursor := transitions(zone, start);
_, found, error := next(*cursor);
assert(error.kind == .NONE && found);
↗