Add toTimestamp method, fix function naming to match Zig conventions

This commit is contained in:
Nathan Fisher 2023-06-13 00:58:55 -04:00
parent e0f4e003d2
commit 7bfdd02688

View File

@ -167,7 +167,7 @@ pub const Offset = union(Sign) {
} }
} }
fn as_seconds(self: Self) i64 { fn asSeconds(self: Self) i64 {
return switch (self) { return switch (self) {
.positive => |ofs| blk: { .positive => |ofs| blk: {
var seconds = @as(i64, ofs.hours) * 3600; var seconds = @as(i64, ofs.hours) * 3600;
@ -189,8 +189,8 @@ test "new offsets" {
} }
test "as seconds" { test "as seconds" {
try testing.expectEqual(Offset.new(-4, 30).?.as_seconds(), -16200); try testing.expectEqual(Offset.new(-4, 30).?.asSeconds(), -16200);
try testing.expectEqual(Offset.new(3, null).?.as_seconds(), 10800); try testing.expectEqual(Offset.new(3, null).?.asSeconds(), 10800);
} }
pub const TimeZone = union(TimeZoneTag) { pub const TimeZone = union(TimeZoneTag) {
@ -250,6 +250,39 @@ pub const DateTime = struct {
.offset => |ofs| ofs, .offset => |ofs| ofs,
}; };
} }
pub fn toTimestamp(self: Self) i64 {
var seconds = 0;
if (self.year.get() < 1970) {
var year = Year.new(1970);
while (year != self.year) {
year = year.previous();
seconds -= year.seconds();
}
} else if (self.year.get() > 1970) {
var year = Year.new(1970);
while (year != self.year) {
seconds += year.seconds();
year = year.next();
}
}
var month = Month.january;
while (month != self.month) {
seconds += month.seconds();
month = month.next().?;
}
seconds += (self.day - 1) * SECONDS_PER_DAY;
if (self.hours) |h| {
seconds += h * 3600;
}
if (self.minutes) |m| {
seconds += m * 60;
}
if (self.seconds) |s| {
seconds += s;
}
return seconds;
}
}; };
test "get year" { test "get year" {