//! ISO-8601 instants, compatible with Java's `Instant.toString()`: //! `2026-01-22T01:48:46Z`, `...46.749Z`, `...46.749629Z` or `...46.749629123Z` //! (0, 3, 6 or 9 fractional digits, whichever is the shortest exact form). const std = @import("std"); const epoch = std.time.epoch; pub const Error = error{InvalidTimestamp}; /// Longest possible output, e.g. `2026-01-22T01:48:46.749629123Z`. pub const max_len = 30; /// Formats nanoseconds since the Unix epoch (UTC). Years must be 1970..9999. pub fn format(buf: *[max_len]u8, unix_ns: i128) []const u8 { const secs: u64 = @intCast(@divFloor(unix_ns, std.time.ns_per_s)); const nanos: u32 = @intCast(@mod(unix_ns, std.time.ns_per_s)); const es = epoch.EpochSeconds{ .secs = secs }; const ym = es.getEpochDay().calculateYearDay(); const md = ym.calculateMonthDay(); const ds = es.getDaySeconds(); var w = std.Io.Writer.fixed(buf); w.print("{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}", .{ ym.year, md.month.numeric(), md.day_index + 1, ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(), }) catch unreachable; if (nanos != 0) { if (nanos % 1_000_000 == 0) { w.print(".{d:0>3}", .{nanos / 1_000_000}) catch unreachable; } else if (nanos % 1_000 == 0) { w.print(".{d:0>6}", .{nanos / 1_000}) catch unreachable; } else { w.print(".{d:0>9}", .{nanos}) catch unreachable; } } w.writeByte('Z') catch unreachable; return w.buffered(); } /// Parses `YYYY-MM-DDTHH:MM:SS[.f{1,9}]Z` into nanoseconds since the Unix epoch. pub fn parse(text: []const u8) Error!i128 { if (text.len < 20 or text[text.len - 1] != 'Z') return error.InvalidTimestamp; if (text[4] != '-' or text[7] != '-' or text[10] != 'T' or text[13] != ':' or text[16] != ':') return error.InvalidTimestamp; const year = try num(text[0..4]); const month = try num(text[5..7]); const day = try num(text[8..10]); const hour = try num(text[11..13]); const minute = try num(text[14..16]); const second = try num(text[17..19]); var nanos: u32 = 0; const rest = text[19 .. text.len - 1]; if (rest.len > 0) { if (rest[0] != '.' or rest.len < 2 or rest.len > 10) return error.InvalidTimestamp; const frac = rest[1..]; nanos = try num(frac); var i: usize = frac.len; while (i < 9) : (i += 1) nanos *= 10; } if (year < 1970 or month < 1 or month > 12 or hour > 23 or minute > 59 or second > 59) return error.InvalidTimestamp; const m: epoch.Month = @enumFromInt(month); const dim = epoch.getDaysInMonth(@intCast(year), m); if (day < 1 or day > dim) return error.InvalidTimestamp; var days: u64 = 0; var y: u32 = 1970; while (y < year) : (y += 1) days += epoch.getDaysInYear(@intCast(y)); var mi: u4 = 1; while (mi < month) : (mi += 1) days += epoch.getDaysInMonth(@intCast(year), @enumFromInt(mi)); days += day - 1; const secs: i128 = @as(i128, days) * epoch.secs_per_day + hour * 3600 + minute * 60 + second; return secs * std.time.ns_per_s + nanos; } fn num(s: []const u8) Error!u32 { for (s) |c| if (!std.ascii.isDigit(c)) return error.InvalidTimestamp; return std.fmt.parseInt(u32, s, 10) catch error.InvalidTimestamp; } fn expectFormat(expected: []const u8, ns: i128) !void { var buf: [max_len]u8 = undefined; try std.testing.expectEqualStrings(expected, format(&buf, ns)); } test "format drops trailing zero groups like Instant.toString" { const base: i128 = 1_769_046_526 * std.time.ns_per_s; // 2026-01-22T01:48:46Z try expectFormat("2026-01-22T01:48:46Z", base); try expectFormat("2026-01-22T01:48:46.749Z", base + 749_000_000); try expectFormat("2026-01-22T01:48:46.749629Z", base + 749_629_000); try expectFormat("2026-01-22T01:48:46.749629123Z", base + 749_629_123); try expectFormat("2026-01-22T01:48:46.000000001Z", base + 1); try expectFormat("1970-01-01T00:00:00Z", 0); } test "parse round-trips" { const base: i128 = 1_769_046_526 * std.time.ns_per_s; for ([_]i128{ 0, base, base + 749_000_000, base + 749_629_000, base + 749_629_123 }) |ns| { var buf: [max_len]u8 = undefined; try std.testing.expectEqual(ns, try parse(format(&buf, ns))); } } test "parse handles leap years and short fractions" { try std.testing.expectEqual(@as(i128, 951_782_400) * std.time.ns_per_s, try parse("2000-02-29T00:00:00Z")); try std.testing.expectEqual(@as(i128, 500_000_000), try parse("1970-01-01T00:00:00.5Z")); } test "parse rejects garbage" { for ([_][]const u8{ "", "2026-01-22", "2026-13-01T00:00:00Z", "2026-02-30T00:00:00Z", "2026-01-22T25:00:00Z", "2026-01-22T01:48:46", "2026-01-22T01:48:46.Z" }) |bad| { try std.testing.expectError(error.InvalidTimestamp, parse(bad)); } } /// Current wall-clock time as nanoseconds since the Unix epoch. pub fn now(io: std.Io) i128 { return std.Io.Timestamp.now(io, .real).nanoseconds; }