Validates Gregorian components without clamping.
#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:
Instants, zones and daylight-saving gaps:
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:
Procedures#
Civil#
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);Combines validated civil components.
day, _ := date(2024, 3, 10);
clock, _ := time_of_day(2, 30, 0);
wall := date_time(day, clock);
assert(wall.date.month == 3 && wall.time.hour == 2);Returns the Gregorian month length after validating year and month.
n, error := days_in_month(2024, 2);
assert(error.kind == .NONE && n == 29);Tests the Gregorian leap rule within the supported year range.
assert(is_leap_year(2000));
assert(!is_leap_year(1900));Returns the ISO weekday after validating the date.
Returns the ordinal day, starting at one.
day, _ := date(2024, 3, 1);
assert(day_of_year(day) == 61);Returns ISO week-year and week number; week one contains January 4.
Validates and converts an ISO week date.
d, error := date_from_iso_week(2024, 1, .MONDAY);
assert(error.kind == .NONE && d.month == 1 && d.day == 1);
_, bad := date_from_iso_week(2021, 53, .MONDAY);
assert(bad.kind == .INVALID_VALUE);Returns the first day of the validated date's month.
d := first_of_month(Date.{ 2024, 3, 15 });
assert(d.day == 1 && d.month == 3);Returns the last day of the validated date's month.
d := last_of_month(Date.{ 2024, 2, 10 });
assert(d.day == 29);Returns 1 January of the validated date's year.
d := first_of_year(Date.{ 2024, 3, 15 });
assert(d.month == 1 && d.day == 1);Returns 31 December of the validated date's year.
d := last_of_year(Date.{ 2024, 3, 15 });
assert(d.month == 12 && d.day == 31);Finds occurrence 1..5 or -1..-5 from the end; missing occurrences fail.
second_sunday, error := nth_weekday_of_month(2024, 3, .SUNDAY, 2);
assert(error.kind == .NONE && second_sunday.day == 10);
last_friday, _ := nth_weekday_of_month(2024, 3, .FRIDAY, -1);
assert(last_friday.day == 29);Applies years/months with month-end policy, then weeks/days; clock units fail.
Instants#
Validates seconds east of UTC, including historical second offsets.
Normalizes signed seconds and nanoseconds, checking representability.
d, error := signed_duration(1, -1);
assert(error.kind == .NONE && d.seconds == 0 && d.nanoseconds == 999999999);Reads Basic.current_time_consensus and converts its Apollo epoch; no new clock path.
instant, error := timestamp_now();
assert(error.kind == .NONE);Converts signed Unix seconds, checking the UTC year range.
instant, error := timestamp_from_seconds(-1);
assert(error.kind == .NONE && instant.seconds == -1);Converts signed Unix milliseconds, checking the UTC year range.
instant, error := timestamp_from_millis(1500);
assert(error.kind == .NONE && instant.seconds == 1 && instant.nanoseconds == 500000000);Converts signed Unix microseconds, checking the UTC year range.
instant, error := timestamp_from_micros(1500000);
assert(error.kind == .NONE && instant.seconds == 1 && instant.nanoseconds == 500000000);Converts signed Unix nanoseconds, checking the UTC year range.
instant, error := timestamp_from_nanos(1500000000);
assert(error.kind == .NONE && instant.seconds == 1 && instant.nanoseconds == 500000000);Returns exact b minus a without calendar interpretation.
a, _ := timestamp_from_seconds(10);
b, _ := timestamp_from_seconds(25);
elapsed := duration_between(a, b);
assert(elapsed.seconds == 15);Spans#
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);Measures b minus a; validates units, positive increments and range.
Measures a minus b; validates units, positive increments and range.
Balances to largest; calendar conversions require a relative value.
span, error := span_balance(.{ minutes = 90 }, .HOUR);
assert(error.kind == .NONE && span.hours == 1 && span.minutes == 30);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);Returns a possibly fractional total; zoned days follow actual day lengths.
hours, error := span_total(.{ hours = 1, minutes = 30 }, .HOUR);
assert(error.kind == .NONE && hours == 1.5);Returns -1/0/1 by elapsed length; calendar units require a shared relative value.
order, error := span_compare(.{ hours = 2 }, .{ minutes = 90 });
assert(error.kind == .NONE && order == 1);Converts clock units to elapsed time; calendar units require a relative value.
d, error := span_to_duration(.{ minutes = 2, seconds = 3 });
assert(error.kind == .NONE && d.seconds == 123);Converts clock units only; years, months, weeks and days are errors.
d, error := duration_from_span(.{ hours = 1 });
assert(error.kind == .NONE && d.seconds == 3600);
_, calendar := duration_from_span(.{ days = 1 });
assert(calendar.kind != .NONE);Reverses every field of a validated span.
s := span_negate(.{ months = 1, days = 2 });
assert(s.months == -1 && s.days == -2);Returns a nonnegative span; span_check rejects signed minima.
Zone load#
Returns the allocation-free UTC zone.
zone := time_zone_utc();
assert(zone.kind == .UTC);Validates and constructs an allocation-free fixed-offset zone.
o, _ := offset(19800);
zone := time_zone_fixed(o);
assert(zone.kind == .FIXED && zone.offset.seconds == 19800);Loads and caches a safe IANA name; directory overrides TZDIR for deterministic fixtures.
zone, error := time_zone_get("America/New_York");
assert(error.kind == .NONE);
defer time_zone_free(*zone);
instant, _ := timestamp_from_seconds(1720000000);
assert(offset_at(zone, instant).seconds == -14400);↗Uses TZ, otherwise /etc/localtime; Windows without TZ returns UNSUPPORTED.
zone, error := time_zone_system();
if error.kind == .NONE {
defer time_zone_free(*zone);
wall := to_civil(zone, timestamp_now());
print("local hour: %\n", wall.time.hour);
}↗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);Parses POSIX TZ rules including M/J/Julian forms and extended transition times.
zone, error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(error.kind == .NONE);
defer time_zone_free(*zone);
summer, _ := parse(Timestamp, "2024-07-01T00:00:00Z");
assert(offset_at(zone, summer).seconds == -14400);Acquires an independent owner; UTC and fixed zones need no reference count.
zone, _ := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
owned := time_zone_retain(zone);
time_zone_free(*zone);
now_instant, _ := timestamp_from_seconds(1720000000);
assert(offset_at(owned, now_instant).seconds == -14400);
time_zone_free(*owned);Releases one owned reference and resets the handle to UTC; borrowed copies become invalid.
zone, _ := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
time_zone_free(*zone);
assert(zone.kind == .UTC);Zoned#
Resolves the offset at an exact instant, using footer rules beyond stored transitions.
zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
winter, _ := timestamp_from_seconds(1704067200);
assert(offset_at(zone, winter).seconds == -18000);Returns a zone-borrowed abbreviation for formatting and conformance.
zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
summer, _ := timestamp_from_seconds(1720000000);
assert(abbreviation_at(zone, summer) == "EDT");Converts an instant in an explicit zone, rejecting civil range overflow.
zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
instant, _ := parse(Timestamp, "2024-03-10T07:30:00Z");
wall := to_civil(zone, instant);
assert(wall.time.hour == 3 && wall.time.minute == 30);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);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);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);Resolves an instant and borrows its zone; the zone owner must outlive the result.
zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
instant, _ := timestamp_from_seconds(1720000000);
z := zoned(instant, zone);
assert(z.offset.seconds == -14400);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);Reads the existing Basic consensus clock in an explicit borrowed zone.
zone := time_zone_utc();
z, error := zoned_now(zone);
assert(error.kind == .NONE && z.offset.seconds == 0);Keeps the instant while borrowing a different zone and resolving its offset.
instant, _ := timestamp_from_seconds(0);
o, _ := offset(32400);
tokyo := with_zone(zoned(instant, time_zone_utc()), time_zone_fixed(o));
assert(tokyo.timestamp.seconds == 0 && tokyo.offset.seconds == 32400);Finds the first valid instant of the local date, including days starting after midnight.
zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
noon, _ := to_zoned(.{ .{ 2024, 3, 10 }, .{ 15, 0, 0, 0 } }, zone);
start, error := start_of_day(noon);
assert(error.kind == .NONE && to_civil(zone, start.timestamp).time.hour == 0);Returns exact elapsed hours between consecutive local day starts.
zone, zone_error := time_zone_from_posix("EST5EDT,M3.2.0,M11.1.0");
assert(zone_error.kind == .NONE);
defer time_zone_free(*zone);
day, _ := to_zoned(.{ .{ 2024, 3, 10 }, .{ 12, 0, 0, 0 } }, zone);
hours, error := hours_in_day(day);
assert(error.kind == .NONE && hours == 23);Ordering#
Orders values (-1/0/1); Zoned and Timestamp use only the instant. Zones order by kind and rule content.
Tests value equality consistent with compare and hash; Zoned ignores its zone.
a, _ := timestamp_from_seconds(5);
b, _ := timestamp_from_seconds(5);
assert(equal(a, b));Hashes semantic fields, never padding or rule pointers; equal values have equal hashes.
Text#
Reads the type's ISO text; Zoned rejects conflicting offsets and accepts bare zone annotations.
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#
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#
Converts the Apollo epoch, rejecting subnanosecond precision instead of discarding it.
instant, error := timestamp_from_apollo(APOLLO_TIME_FOR_JAN_1_1970);
assert(error.kind == .NONE && instant.seconds == 0);Converts a validated instant to Basic's femtosecond Apollo representation.
instant, _ := timestamp_from_seconds(60);
apollo := timestamp_to_apollo(instant);
back, error := timestamp_from_apollo(apollo);
assert(error.kind == .NONE && equal(back, instant));Treats Apollo as a duration (no epoch); subnanosecond input fails.
span, _ := signed_duration(5);
apollo := duration_to_apollo(span);
back, error := duration_from_apollo(apollo);
assert(error.kind == .NONE && back.seconds == 5);Converts an exact duration without adding an epoch.
span, _ := signed_duration(5);
apollo := duration_to_apollo(span);
back, _ := duration_from_apollo(apollo);
assert(equal(back, span));Validates Basic's zero-based components; ignores zone and derived weekday metadata.
calendar, _ := date_time_to_calendar(.{ .{ 2024, 2, 29 }, .{ 12, 30, 0, 0 } });
wall, error := date_time_from_calendar(calendar);
assert(error.kind == .NONE && wall.date.day == 29 && wall.time.hour == 12);Converts a civil reading as UTC-tagged fields; rejects submillisecond precision.
calendar, error := date_time_to_calendar(.{ .{ 2024, 2, 29 }, .{ 12, 30, 0, 0 } });
assert(error.kind == .NONE && calendar.month_starting_at_0 == 1 && calendar.day_of_month_starting_at_0 == 28);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#
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-01A 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);A wall-clock value, not an instant.
Date_Time :: struct {
date: Date;
time: Time_Of_Day;
}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);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);Seconds east of UTC, within +/-25:59:59.
Offset :: struct {
seconds: s32;
}The representation of a zone.
Time_Zone_Kind :: enum u8 {
UTC;
FIXED;
RULES;
}assert(time_zone_utc().kind == .UTC);
o, _ := offset(3600);
assert(time_zone_fixed(o).kind == .FIXED);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);An instant and a borrowed zone, with its resolved offset.
instant, _ := timestamp_from_seconds(0);
z := zoned(instant, time_zone_utc());
assert(z.timestamp.seconds == 0 && z.offset.seconds == 0);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);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);ISO weekday numbering; e.g. weekday(value) returns MONDAY for 2024-03-11.
Weekday :: enum u8 {
MONDAY :: 1;
TUESDAY;
WEDNESDAY;
THURSDAY;
FRIDAY;
SATURDAY;
SUNDAY;
}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);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);Month-end handling; e.g. January 31 plus one month constrains to February's last day.
Overflow :: enum u8 {
CONSTRAIN;
REJECT;
}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;
}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;
}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;
}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");A constant-space cursor borrowing a 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);
start, _ := timestamp_from_seconds(1704067200);
cursor := transitions(zone, start);
_, found, error := next(*cursor);
assert(error.kind == .NONE && found);