//! Very basic ISO 8601 parsing with pretty simple seconds from epoch conversion. const std = @import("std"); const Allocator = std.mem.Allocator; // const logger = std.log.scoped(.datetime); const Self = @This(); pub const Length = "YYYY-mm-ddTHH:MM:SSZ".len; const DefaultFormat = "Y-m-dTH:M:SZ"; const secs_per_day: u64 = 24 * 60 * 60; const Error = error{ ParseError, }; const Cache = struct { year: std.time.epoch.Year = 1970, month: std.time.epoch.Month = .jan, day: u5 = 0, hour: u5 = 0, minute: u6 = 0, second: u6 = 0, offset: i32 = 0, // seconds pub fn formatNumber(self: Cache, writer: *std.Io.Writer, options: anytype) std.Io.Writer.Error!void { _ = options; return writer.print("{d}", .{self.toEpochSeconds()}); } /// To seconds since epoch. pub fn toEpochSeconds(self: Cache) i64 { var remain: u64 = self.second; remain += @as(u64, self.minute) * 60; remain += @as(u64, self.hour) * 60 * 60; remain += @as(u64, self.day - 1) * secs_per_day; //const leap_year: std.time.epoch.YearLeapKind = if (std.time.epoch.isLeapYear(self.year)) .leap else .not_leap; var month: std.time.epoch.Month = .jan; while (month != self.month) { const secs_in_month: u64 = std.time.epoch.getDaysInMonth(self.year, month) * secs_per_day; remain += secs_in_month; month = @enumFromInt(@intFromEnum(month) + 1); } var year: std.time.epoch.Year = 1970; // Step through years. while (year != self.year) { const secs_in_year = secs_per_day * std.time.epoch.getDaysInYear(year); remain += secs_in_year; year += 1; } return @as(i64, @intCast(remain)) - self.offset; } pub fn fromEpochSeconds(epoch: i64, offset: i32) Cache { if (epoch == 0) { return .{ .year = 1970, .month = .jan, .day = 1, .hour = 0, .minute = 0, .second = 0, .offset = offset, }; } var remain: u64 = @intCast(epoch + offset); var year: std.time.epoch.Year = 1970; var secs_in_year: u64 = secs_per_day * std.time.epoch.getDaysInYear(year); // Step through years. while (remain > secs_in_year) { year += 1; remain -= secs_in_year; secs_in_year = secs_per_day * std.time.epoch.getDaysInYear(year); } //const leap_year: std.time.epoch.YearLeapKind = if (std.time.epoch.isLeapYear(year)) .leap else .not_leap; var month: std.time.epoch.Month = .jan; var secs_in_month: u64 = std.time.epoch.getDaysInMonth(year, month) * secs_per_day; // Step through months of the year. while (remain > secs_in_month) { month = @enumFromInt(@intFromEnum(month) + 1); remain -= secs_in_month; secs_in_month = std.time.epoch.getDaysInMonth(year, month) * secs_per_day; } const day = @divFloor(remain, secs_per_day); remain = @rem(remain, secs_per_day); const hour = @divFloor(remain, 60 * 60); remain = @rem(remain, 60 * 60); const minute = @divFloor(remain, 60); const second = @rem(remain, 60); return .{ .year = year, .month = month, .day = @intCast(day + 1), .hour = @intCast(hour), .minute = @intCast(minute), .second = @intCast(second), .offset = offset, }; } }; timestamp: std.Io.Timestamp = .zero, offset: i32 = 0, // seconds cache: ?Cache = null, const Format = "YYYY-mm-ddTHH:MM:SS"; /// Parse ISO 8601 'YYYY-mm-ddTHH:MM:SS' pub fn parse(value: []const u8) !Self { var self: Self = .{}; // 0123-56-89-12:45:78 // 1234-67-90-23:56:89 // YYYY-mm-ddTHH:MM:SS if (value.len == Format.len and value[4] == '-' and value[7] == '-' and (value[10] == 'T' or value[10] == ' ') and value[13] == ':' and value[16] == ':') { self.cache = .{ .year = try std.fmt.parseInt(u16, value[0..4], 10), .month = @enumFromInt(try std.fmt.parseInt(u4, value[5..7], 10)), .day = try std.fmt.parseInt(u5, value[8..10], 10), .hour = try std.fmt.parseInt(u5, value[11..13], 10), .minute = try std.fmt.parseInt(u6, value[14..16], 10), .second = try std.fmt.parseInt(u6, value[17..19], 10), }; self.timestamp = .fromNanoseconds(self.cache.?.toEpochSeconds() * NanoMultiplier); return self; } return error.ParseError; } /// Parse a given format. pub fn parseFormat(fmt: []const u8, value: []const u8) !Self { var cache: Cache = .{}; var pos: usize = 0; const monthInfo = @typeInfo(std.time.epoch.Month).@"enum"; for (fmt) |fchar| { switch (fchar) { 'b' => { const needle = value[pos .. pos + 3]; inline for (monthInfo.fields) |field| { if (std.ascii.eqlIgnoreCase(field.name, needle)) { cache.month = @enumFromInt(field.value); pos += 3; break; } } }, 'd' => { cache.day = try std.fmt.parseInt(u5, value[pos .. pos + 2], 10); pos += 2; }, 'Y' => { cache.year = try std.fmt.parseInt(u16, value[pos .. pos + 4], 10); pos += 4; }, 'm' => { cache.month = @enumFromInt(try std.fmt.parseInt(u4, value[pos .. pos + 2], 10)); pos += 2; }, 'H' => { cache.hour = try std.fmt.parseInt(u5, value[pos .. pos + 2], 10); pos += 2; }, 'M' => { cache.minute = try std.fmt.parseInt(u6, value[pos .. pos + 2], 10); pos += 2; }, 'S' => { cache.second = try std.fmt.parseInt(u6, value[pos .. pos + 2], 10); pos += 2; }, else => pos += 1, } } var self: Self = .{ .cache = cache }; self.timestamp = .fromNanoseconds(self.cache.?.toEpochSeconds() * NanoMultiplier); return self; } /// Default formatter long form string. pub fn format(self: Self, writer: *std.Io.Writer) std.Io.Writer.Error!void { return self._format(DefaultFormat, writer); } pub fn formatNumber(self: Self, writer: *std.Io.Writer, options: anytype) std.Io.Writer.Error!void { _ = options; return writer.print("{d}", .{self.timestamp.toSeconds()}); } /// To format as a timestamp. /// Usage: std.fmt.alt(yourTimestamp, .timestampFormatter) pub fn timestampFormatter(self: Self, writer: *std.Io.Writer) std.Io.Writer.Error!void { return writer.print("{d}", .{self.timestamp.toSeconds()}); } const Formatter = struct { dtval: Self, fmt: []const u8, pub inline fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void { try self.dtval._format(self.fmt, writer); } }; pub fn formatter(self: Self, fmt: []const u8) Formatter { return .{ .dtval = self, .fmt = fmt }; } pub fn defaultFormatter(self: Self) Formatter { return .{ .dtval = self, .fmt = DefaultFormat }; } /// Formatting using our own simple format string. fn _format(self: Self, fmt: []const u8, writer: *std.Io.Writer) std.Io.Writer.Error!void { const cache: Cache = if (self.cache != null and self.cache.?.offset == self.offset) self.cache.? else .fromEpochSeconds(@intCast(self.timestamp.toSeconds()), self.offset); const nanoseconds: i96 = @rem(self.timestamp.nanoseconds, NanoMultiplier); for (fmt) |c| { switch (c) { 'Y' => try writer.print("{d:0>4}", .{cache.year}), 'm' => try writer.print("{d:0>2}", .{@intFromEnum(cache.month)}), 'b' => try writer.print("{t}", .{cache.month}), 'd' => try writer.print("{d:0>2}", .{cache.day}), 'H' => try writer.print("{d:0>2}", .{cache.hour}), 'M' => try writer.print("{d:0>2}", .{cache.minute}), 'S' => try writer.print("{d:0>2}", .{cache.second}), 'f' => try writer.print("{d:0>6}", .{@as(u96, @intCast(@divFloor(nanoseconds, 1000)))}), else => try writer.print("{c}", .{c}), } } } const NanoMultiplier: i96 = 1000000000; /// Parsed now. pub fn now(io: std.Io) Self { return fromTimestamp(.now(io, .real)); } /// Fairly simple conversion of seconds since epoch into parsed datetime. pub fn fromTimestamp(timestamp: std.Io.Timestamp) Self { return .{ .timestamp = timestamp }; } /// JSON stringify. pub fn stringify(self: Self, allocator: Allocator) ![]const u8 { return self.stringifyFormat(allocator, DefaultFormat); } pub fn jsonStringify(self: Self, jw: anytype) std.Io.Writer.Error!void { var tmp: [Length]u8 = undefined; var fbs = std.Io.Writer.fixed(&tmp); try self._format(DefaultFormat, &fbs); try jw.write(fbs.buffered()); } /// Stringify using our simple format string. pub fn stringifyFormat(self: Self, allocator: Allocator, fmt: []const u8) ![]const u8 { var writer: std.Io.Writer.Allocating = .init(allocator); try self._format(fmt, &writer.writer); return writer.toOwnedSlice(); } test now { const a1 = now(std.testing.io); const e1: Self = .{}; var abuf: [64]u8 = undefined; var ebuf: [64]u8 = undefined; const aslice = try std.fmt.bufPrint(&abuf, "{f}", .{a1}); const eslice = try std.fmt.bufPrint(&ebuf, "{f}", .{e1}); try std.testing.expect(std.mem.eql(u8, aslice, eslice) == false); } test parse { const a1 = try parse("1970-01-02T03:04:05"); const e1: Cache = .{ .day = 2, .month = .jan, .year = 1970, .hour = 3, .minute = 4, .second = 5, }; try std.testing.expectEqual(a1.cache.?, e1); } test parseFormat { const a1 = try parseFormat("d/b/Y:H:M:S", "18/Dec/2024:09:55:09 +0000"); const e1: Cache = .{ .day = 18, .month = .dec, .year = 2024, .hour = 9, .minute = 55, .second = 9, }; try std.testing.expectEqual(a1.cache.?, e1); } test "fromEpochSeconds" { const a1: Cache = .fromEpochSeconds(1737478323, 0); const e1: Cache = .{ .year = 2025, .month = .jan, .day = 21, .hour = 16, .minute = 52, .second = 3, }; try std.testing.expectEqual(a1, e1); } test "toEpochSeconds" { const a1: Cache = .{ .year = 2025, .month = .jan, .day = 21, .hour = 16, .minute = 52, .second = 3, }; const e1 = 1737478323; try std.testing.expectEqual(a1.toEpochSeconds(), e1); var buf: [64]u8 = undefined; try std.testing.expectEqualStrings("1737478323", try std.fmt.bufPrint(&buf, "{d}", .{a1})); } test formatter { const a1 = fromTimestamp(.fromNanoseconds(@as(i96, 1737478323) * NanoMultiplier)); var buf: [128]u8 = undefined; var writer: std.Io.Writer = .fixed(&buf); try writer.print("{f}", .{a1.formatter("Y H S")}); try std.testing.expectEqualStrings("2025 16 03", writer.buffered()); } test "format f" { const a1: Self = .{ .timestamp = .fromNanoseconds(1737478323 * NanoMultiplier + 123456) }; var abuf: [64]u8 = undefined; const aslice = try std.fmt.bufPrint(&abuf, "{f}", .{a1.formatter("f")}); try std.testing.expectEqualStrings(aslice, "000123"); }