1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//! atproto datetime syntax — https://atproto.com/specs/lexicon#datetime
//!
//! the pinned atproto profile of RFC 3339 — stricter than the RFC, and the
//! spec text pins each divergence:
//! - upper-case 'T' and 'Z' required ("lower-case is not allowed")
//! - timezone required; "-00:00" ("negative zero") specifically disallowed
//! - "Datetimes before year zero ... are specifically disallowed" — enforced
//! on the NORMALIZED instant, so an offset cannot smuggle one in
//! - fraction: "arbitrary fractional precision digits are allowed"; parsed
//! at microsecond precision (truncation is the spec's own acknowledged
//! "loss-of-precision" round-trip ambiguity)
//! - second 60 (leap second) is not in the profile's grammar and is
//! rejected. general RFC 3339 parsers differ here (rust's jiff clamps
//! :60 to the last instant of :59; chrono represents-but-ignores) — a
//! deliberate divergence from them, matching the interop-fixture-passing
//! validator this type replaces.
//! validated against the atproto interop fixtures (interop_tests.zig runs
//! Datetime.parse over datetime_syntax_valid / _invalid / _parse_invalid).
//!
//! this type exists because the string↔instant conversion kept being
//! hand-rolled: two byte-identical formatRfc3339s in stream, a 45-line
//! parser in the jetstream SDK example. parse and format live here, next
//! to the rest of the atproto syntax family (Tid, Did, Nsid, Rkey).
const std = @import("std");
/// microseconds since the unix epoch, UTC. negative = before 1970.
micros: i64,
/// canonical rendering length: "YYYY-MM-DDTHH:MM:SS.ffffffZ".len = 27
pub const string_len = "YYYY-MM-DDTHH:MM:SS.ffffffZ".len;
/// millisecond rendering length: "YYYY-MM-DDTHH:MM:SS.fffZ".len = 24
pub const millis_string_len = "YYYY-MM-DDTHH:MM:SS.fffZ".len;
pub fn fromMicros(micros: i64) @This() {
return .{ .micros = micros };
}
/// the instant `seconds` after the unix epoch (negative = before 1970).
/// null outside the years 0000 through 9999, which the profile's
/// four-digit year cannot render.
pub fn fromSeconds(seconds: i64) ?@This() {
return fromScaled(seconds, std.time.us_per_s);
}
/// the instant `millis` after the unix epoch, as JavaScript's `Date` holds
/// it. null outside the years 0000 through 9999.
pub fn fromMillis(millis: i64) ?@This() {
return fromScaled(millis, std.time.us_per_ms);
}
fn fromScaled(value: i64, us_per_unit: i64) ?@This() {
const micros = std.math.mul(i64, value, us_per_unit) catch return null;
if (micros < min_micros or micros > max_micros) return null;
return .{ .micros = micros };
}
/// parse the full atproto datetime profile, applying any UTC offset.
/// null on syntactic or semantic invalidity (month 0, Feb 30, hour 25,
/// "-00:00", instants before year 0). fractional digits beyond
/// microseconds are truncated.
pub fn parse(s: []const u8) ?@This() {
if (s.len < "0000-01-01T00:00:00Z".len or s.len > 64) return null;
const head = s[0.."0000-01-01T00:00:00".len];
const delimiters = [_]struct { u5, u8 }{
.{ 4, '-' },
.{ 7, '-' },
.{ 10, 'T' },
.{ 13, ':' },
.{ 16, ':' },
};
for (delimiters) |delimiter|
if (head[delimiter[0]] != delimiter[1])
return null;
const year = parse4(head[0..4]) orelse return null;
const month = parse2(head[5..7], 12) orelse return null;
if (month == 0)
return null;
const day = parse2(head[8..10], daysInMonth(year, month)) orelse return null;
if (day == 0)
return null;
const hour = parse2(head[11..13], 23) orelse return null;
const minute = parse2(head[14..16], 59) orelse return null;
const second = parse2(head[17..], 59) orelse return null;
const pos, const frac_us = if (s[head.len] == '.') pos: {
const start = head.len + 1;
const len = @min(20, s.len - start);
var frac_us: u32 = 0;
var scale: u32 = 100_000;
const frac_len = for (s[start..][0..len], 0..) |c, i| {
if (c < '0' or c > '9')
break i;
if (scale > 0) {
frac_us += scale * (c - '0');
scale /= 10;
}
} else len;
if (frac_len == 0)
return null;
const pos = start + frac_len;
if (pos == s.len)
return null
else
break :pos .{ pos, frac_us };
} else .{ head.len, 0 };
const offset_minutes = offset_minutes: {
const tz_sign: i12 = switch (s[pos]) {
'Z' => if (pos + 1 != s.len)
return null
else
break :offset_minutes 0,
'+' => 1,
'-' => -1,
else => return null,
};
const remaining = if (pos + 6 == s.len)
s[pos + 1 ..][0..5]
else
return null;
if (remaining[2] != ':')
return null;
const tz_hour = parse2(remaining[0..2], 23) orelse return null;
const tz_minute = parse2(remaining[3..], 59) orelse return null;
// RFC 3339 §4.3: "-00:00" means "offset unknown" and the
// atproto profile rejects it
if (tz_sign < 0 and tz_hour == 0 and tz_minute == 0) return null;
break :offset_minutes tz_sign * (@as(i12, tz_hour) * 60 + tz_minute);
};
const civil: Civil = .{
.year = year,
.month = month,
.day = day,
};
const days = civil.daysSinceUnixEpoch();
const local_micros = days * std.time.us_per_day +
(@as(i64, hour) * 3600 + @as(i64, minute) * 60 + @as(i64, second)) * std.time.us_per_s +
frac_us;
const utc_micros = local_micros - @as(i64, offset_minutes) * std.time.us_per_min;
// the profile's floor: nothing normalizes before 0000-01-01T00:00:00Z
// (this generalizes the fixtures' "normalizes to a negative time" case)
if (utc_micros < min_micros) return null;
return .{ .micros = utc_micros };
}
/// canonical atproto form, microsecond precision, always 'Z':
/// "1985-04-12T23:20:50.123456Z". the instant must lie in years 0000-9999.
pub fn toString(self: @This()) [string_len]u8 {
return self.render(6);
}
/// millisecond precision, always 'Z': "1985-04-12T23:20:50.123Z", the form
/// JavaScript's `Date.prototype.toISOString` emits and the reference PDS
/// writes. sub-millisecond digits are truncated toward the past. the instant
/// must lie in years 0000-9999.
pub fn toStringMillis(self: @This()) [millis_string_len]u8 {
return self.render(3);
}
fn render(self: @This(), comptime frac_digits: comptime_int) ["YYYY-MM-DDTHH:MM:SS.Z".len + frac_digits]u8 {
std.debug.assert(self.micros >= min_micros and self.micros <= max_micros);
const days = @divFloor(self.micros, std.time.us_per_day);
const day_us = self.micros - days * std.time.us_per_day;
const civil: Civil = .fromDays(days);
const day_s: u64 = @intCast(@divTrunc(day_us, std.time.us_per_s));
const frac: u64 = @intCast(@divTrunc(@mod(day_us, std.time.us_per_s), std.math.pow(i64, 10, 6 - frac_digits)));
var buf: ["YYYY-MM-DDTHH:MM:SS.Z".len + frac_digits]u8 = undefined;
_ = std.fmt.bufPrint(&buf, "{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}.{d:0>" ++ std.fmt.comptimePrint("{d}", .{frac_digits}) ++ "}Z", .{
@as(u64, @intCast(civil.year)),
civil.month,
civil.day,
day_s / 3600,
(day_s % 3600) / 60,
day_s % 60,
frac,
}) catch unreachable;
return buf;
}
/// 0000-01-01T00:00:00Z in unix-epoch microseconds
const min_micros: i64 = Civil.unix_epoch.daysSinceUnixEpoch() * std.time.us_per_day;
/// 9999-12-31T23:59:59.999999Z in unix-epoch microseconds
const max_micros: i64 = (Civil{ .year = 10000, .month = 1, .day = 1 }).daysSinceUnixEpoch() * std.time.us_per_day - 1;
fn parse2(s: *const [2]u8, upperbound: anytype) ?switch (@TypeOf(upperbound)) {
comptime_int => std.math.IntFittingRange(0, upperbound),
void => u7,
else => |T| T,
} {
const a, const b = s.*;
if (a < '0' or a > '9' or b < '0' or b > '9') return null;
const val = @as(u7, @intCast(a - '0')) * 10 + @as(u4, @intCast(b - '0'));
if (@TypeOf(upperbound) != void and val > upperbound)
return null;
return @intCast(val);
}
fn parse4(s: *const [4]u8) ?u14 {
const hi = parse2(s[0..2], {}) orelse return null;
const lo = parse2(s[2..], {}) orelse return null;
return @as(u14, hi) * 100 + lo;
}
fn isLeap(year: u14) bool {
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0;
}
fn daysInMonth(year: u14, month: u4) u5 {
return switch (month) {
1, 3, 5, 7, 8, 10, 12 => 31,
4, 6, 9, 11 => 30,
2 => if (isLeap(year)) 29 else 28,
else => 0,
};
}
const Civil = struct {
year: i64,
month: u4,
day: u5,
const unix_epoch: @This() = .{
.year = 0,
.month = 1,
.day = 1,
};
const constants = enum {
const magic_leap_year = 400;
const max_yoe = magic_leap_year - 1; // 399
const max_doy = 365;
const max_doe = max_yoe * max_doy + (max_yoe / 4) - (max_yoe / 100) + max_doy; // 146096
const min_no_of_leap_years_in_a_century = 100 / 4 - 1; // 24
const some_magic = 153;
const unix_epoch_days_offset = 719468;
};
/// Hinnant's civil_from_days: inverse of daysFromCivil.
fn fromDays(z0: i64) @This() {
const z = z0 + constants.unix_epoch_days_offset;
const era = @divFloor(z, constants.max_doe + 1);
const doe = z - era * (constants.max_doe + 1); // [0, 146096]
const yoe = @divFloor(doe - @divFloor(doe, constants.max_doy * 4) + @divFloor(doe, constants.max_doy * 100 + constants.min_no_of_leap_years_in_a_century) - @divFloor(doe, constants.max_doe), constants.max_doy); // [0, 399]
const y = yoe + era * constants.magic_leap_year;
const doy = doe - (constants.max_doy * yoe + @divFloor(yoe, 4) - @divFloor(yoe, 100)); // [0, 365]
const mp = @divFloor(5 * doy + 2, constants.some_magic); // [0, 11]
const d = doy - @divFloor(constants.some_magic * mp + 2, 5) + 1; // [1, 31]
const m = if (mp < 10) mp + 3 else mp - 9; // [1, 12]
return .{ .year = if (m <= 2) y + 1 else y, .month = @intCast(m), .day = @intCast(d) };
}
/// Howard Hinnant's days_from_civil: days since 1970-01-01 for a proleptic
/// Gregorian date. exact over the whole 0000..9999 profile, unlike
/// std.time.epoch which is unsigned and 1970-anchored.
fn daysSinceUnixEpoch(self: @This()) i64 {
const y = if (self.month <= 2) self.year - 1 else self.year;
const era = @divFloor(y, constants.magic_leap_year);
const yoe = y - era * constants.magic_leap_year; // [0, 399]
const mp: u4 = @intCast(@mod(@as(u5, self.month) + 9, 12)); // Mar=0 .. Feb=11
const doy: u9 = @intCast(@divFloor(@as(u11, constants.some_magic) * mp + 2, 5) + self.day - 1); // [0, 365]
const doe = yoe * constants.max_doy + @divFloor(yoe, 4) - @divFloor(yoe, 100) + doy; // [0, 146096]
return era * (constants.max_doe + 1) + doe - constants.unix_epoch_days_offset;
}
};
// === tests ===
// the atproto interop fixtures run against Datetime.parse in
// interop_tests.zig; these pin the numeric semantics fixtures can't.
const testing = std.testing;
test "parse and toString round-trip the canonical form" {
const dt = parse("1985-04-12T23:20:50.123456Z").?;
try testing.expectEqual(482196050123456, dt.micros);
try testing.expectEqualStrings("1985-04-12T23:20:50.123456Z", &dt.toString());
}
test "offsets normalize to UTC" {
const utc = parse("1985-04-12T23:20:50.123Z").?;
const minus7 = parse("1985-04-12T16:20:50.123-07:00").?;
const plus145 = parse("1985-04-13T01:05:50.123+01:45").?;
try testing.expectEqual(utc.micros, minus7.micros);
try testing.expectEqual(utc.micros, plus145.micros);
}
test "fraction truncates past microseconds; short fractions scale" {
try testing.expectEqual(
parse("1985-04-12T23:20:50.123456Z").?.micros,
parse("1985-04-12T23:20:50.1234567891Z").?.micros,
);
try testing.expectEqual(
482196050100000,
parse("1985-04-12T23:20:50.1Z").?.micros,
);
}
test "epoch identities and pre-1970 instants" {
try testing.expectEqual(0, parse("1970-01-01T00:00:00Z").?.micros);
const pre = parse("1969-12-31T23:59:59.000001Z").?;
try testing.expectEqual(-999_999, pre.micros);
try testing.expectEqualStrings("1969-12-31T23:59:59.000001Z", &pre.toString());
}
test "the year-zero floor is an instant rule, not a string rule" {
try testing.expect(parse("0000-01-01T00:00:00Z") != null);
try testing.expect(parse("0000-01-01T00:00:00+00:00") != null);
// anything that NORMALIZES before the floor is out, not just the
// fixtures' exact case
try testing.expect(parse("0000-01-01T00:00:00+01:00") == null);
try testing.expect(parse("0000-01-01T00:30:00+01:00") == null);
}
test "rejects the profile's forbidden shapes" {
try testing.expect(parse("1985-04-12T23:20:50.123-00:00") == null); // unknown offset
try testing.expect(parse("1985-04-12T23:20:61.123Z") == null); // semantic
try testing.expect(parse("1985-02-30T00:00:00Z") == null); // Feb 30
try testing.expect(parse("1985-04-12 23:20:50.123Z") == null); // space separator
try testing.expect(parse("1985-04-12T23:20:50.Z") == null); // empty fraction
try testing.expect(parse("1985-04-12T23:20:50") == null); // no timezone
}
test "leap handling matches the calendar both directions" {
const feb29 = parse("2024-02-29T12:00:00Z").?;
try testing.expectEqualStrings("2024-02-29T12:00:00.000000Z", &feb29.toString());
try testing.expect(parse("2023-02-29T12:00:00Z") == null);
try testing.expect(parse("1900-02-29T12:00:00Z") == null); // century non-leap
try testing.expect(parse("2000-02-29T12:00:00Z") != null); // 400-year leap
}
test "toStringMillis renders the JavaScript toISOString form" {
try testing.expectEqualStrings("1970-01-01T00:00:00.000Z", &fromSeconds(0).?.toStringMillis());
try testing.expectEqualStrings("2026-10-01T00:00:00.000Z", &fromSeconds(1790812800).?.toStringMillis());
try testing.expectEqualStrings("2023-04-12T04:53:57.057Z", &fromMillis(1681275237057).?.toStringMillis());
// sub-millisecond digits truncate toward the past, before and after 1970
try testing.expectEqualStrings("1985-04-12T23:20:50.123Z", &parse("1985-04-12T23:20:50.123999Z").?.toStringMillis());
try testing.expectEqualStrings("1969-12-31T23:59:59.999Z", &fromMicros(-1).toStringMillis());
try testing.expectEqualStrings("1969-12-31T23:59:59.000000Z", &fromSeconds(-1).?.toString());
}
test "fromSeconds and fromMillis cover exactly the four-digit years" {
try testing.expectEqualStrings("0000-01-01T00:00:00.000Z", &fromSeconds(-62167219200).?.toStringMillis());
try testing.expect(fromSeconds(-62167219201) == null);
try testing.expectEqualStrings("9999-12-31T23:59:59.999Z", &fromMillis(253402300799999).?.toStringMillis());
try testing.expect(fromMillis(253402300800000) == null);
try testing.expect(fromSeconds(std.math.minInt(i64)) == null);
try testing.expect(fromSeconds(std.math.maxInt(i64)) == null);
try testing.expectEqual(parse("2024-02-29T12:00:00Z").?.micros, fromSeconds(1709208000).?.micros);
}