diff --git a/src/main.zig b/src/main.zig index ffe0607..ac30bc9 100644 --- a/src/main.zig +++ b/src/main.zig @@ -206,6 +206,25 @@ pub const DateTime = struct { } try writer.print("{s}", .{self.tz}); } + + pub fn format_basic( + self: Self, + writer: anytype, + ) !void { + try writer.print("{s}{d:0>2}{d:0>2}", .{ + self.year, @enumToInt(self.month), self.day, + }); + if (self.hour) |h| { + try writer.print("T{d:0>2}", .{h}); + if (self.minute) |m| { + try writer.print("{d:0>2}", .{m}); + if (self.second) |s| { + try writer.print("{d:0>2}", .{s}); + } + } + } + try self.tz.format_basic(writer); + } }; test "new year" { @@ -447,3 +466,28 @@ test "custom fmt" { try testing.expect(mem.eql(u8, dt_string, "2023-06-10T06:21:22Z")); debug.print("Passed\n", .{}); } + +test "fmt basic" { + const dt = DateTime{ + .year = Year.new(2023), + .month = .june, + .day = 10, + .hour = 6, + .minute = 21, + .second = 22, + .tz = TimeZone.new(-4, null).?, + }; + var dt_array = std.ArrayList(u8).init(testing.allocator); + defer dt_array.deinit(); + var writer = dt_array.writer(); + try dt.format_basic(writer); + try testing.expect(mem.eql(u8, dt_array.items, "20230610T062122-04")); + const dt_string = try std.fmt.allocPrint( + testing.allocator, + "{s}", + .{dt}, + ); + defer testing.allocator.free(dt_string); + try testing.expect(mem.eql(u8, dt_string, "2023-06-10T06:21:22-04")); + debug.print("Passed\n", .{}); +} diff --git a/src/timezone.zig b/src/timezone.zig index a83b4c8..5e6e380 100644 --- a/src/timezone.zig +++ b/src/timezone.zig @@ -100,4 +100,27 @@ pub const TimeZone = union(TimeZoneTag) { }, } } + + pub fn format_basic( + self: Self, + writer: anytype, + ) !void { + switch (self) { + .utc => try writer.writeAll("Z"), + .offset => |ofs| switch (ofs) { + .positive => |p| { + try writer.print("+{d:0>2}", .{p.hours}); + if (p.minutes) |m| { + try writer.print("{d:0>2}", .{m}); + } + }, + .negative => |n| { + try writer.print("-{d:0>2}", .{n.hours}); + if (n.minutes) |m| { + try writer.print("{d:0>2}", .{m}); + } + }, + }, + } + } };