From c79292181ad11bcd870e47e7a3c84836962d7d4c Mon Sep 17 00:00:00 2001 From: Nathan Fisher Date: Tue, 13 Jun 2023 12:22:59 -0400 Subject: [PATCH] Add DateTime.compare for comparisons and ordering --- src/main.zig | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/src/main.zig b/src/main.zig index f43818e..36ea861 100644 --- a/src/main.zig +++ b/src/main.zig @@ -238,6 +238,12 @@ pub const WeekDay = enum(u3) { wednesday, }; +pub const Comparison = enum { + gt, + lt, + eq, +}; + pub const DateTime = struct { year: Year, month: Month, @@ -301,6 +307,12 @@ pub const DateTime = struct { const days = @divTrunc(ts, SECONDS_PER_DAY); return @intToEnum(WeekDay, @rem(days, 7)); } + + pub fn compare(self: Self, other: Self) Comparison { + const a = self.toTimestamp(); + const b = other.toTimestamp(); + return if (a > b) .gt else if (a < b) .lt else .eq; + } }; test "get year" { @@ -380,3 +392,47 @@ test "get weekday 2" { }; try testing.expectEqual(dt.weekday(), .saturday); } + +test "ordering lt" { + const a = DateTime{ + .year = Year.new(2023), + .month = .june, + .day = 10, + .hour = 6, + .minute = 21, + .second = 22, + .tz = .utc, + }; + const b = DateTime{ + .year = Year.new(2023), + .month = .june, + .day = 10, + .hour = 6, + .minute = 21, + .second = 23, + .tz = .utc, + }; + try testing.expectEqual(a.compare(b), .lt); +} + +test "ordering gt" { + const a = DateTime{ + .year = Year.new(2023), + .month = .june, + .day = 10, + .hour = 6, + .minute = 21, + .second = 22, + .tz = .utc, + }; + const b = DateTime{ + .year = Year.new(2023), + .month = .june, + .day = 10, + .hour = 6, + .minute = 21, + .second = 22, + .tz = TimeZone.new(1, null).?, + }; + try testing.expectEqual(a.compare(b), .gt); +}