Add DateTime.compare for comparisons and ordering

This commit is contained in:
Nathan Fisher 2023-06-13 12:22:59 -04:00
parent 66b9e61ed4
commit c79292181a
1 changed files with 56 additions and 0 deletions

View File

@ -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);
}