diff --git a/src/main.zig b/src/main.zig index d7e2c9d..e2da630 100644 --- a/src/main.zig +++ b/src/main.zig @@ -167,7 +167,7 @@ pub const Offset = union(Sign) { } } - fn as_seconds(self: Self) i64 { + fn asSeconds(self: Self) i64 { return switch (self) { .positive => |ofs| blk: { var seconds = @as(i64, ofs.hours) * 3600; @@ -189,8 +189,8 @@ test "new offsets" { } test "as seconds" { - try testing.expectEqual(Offset.new(-4, 30).?.as_seconds(), -16200); - try testing.expectEqual(Offset.new(3, null).?.as_seconds(), 10800); + try testing.expectEqual(Offset.new(-4, 30).?.asSeconds(), -16200); + try testing.expectEqual(Offset.new(3, null).?.asSeconds(), 10800); } pub const TimeZone = union(TimeZoneTag) { @@ -250,6 +250,39 @@ pub const DateTime = struct { .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" {