Add format_basic
method to format as ISO-8601 without field separators
This commit is contained in:
parent
54251ea116
commit
1b56c10dc2
44
src/main.zig
44
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", .{});
|
||||
}
|
||||
|
@ -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});
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
|
Loading…
Reference in New Issue
Block a user