const std = @import("std"); const Date = @This(); year: u16, month: u8, day: u8, /// M1-CSV-016: whatever the input format, generated dates use YYYY-MM-DD. pub fn format(self: Date, writer: *std.Io.Writer) std.Io.Writer.Error!void { try writer.print("{d:0>4}-{d:0>2}-{d:0>2}", .{ self.year, self.month, self.day }); } pub const Format = enum { dotted, /// Dotted with a two-digit year. dotted_short, iso, pub const all = std.enums.values(Format); /// The spelling of each of `all`, in the same order. pub const patterns = blk: { var spellings: [all.len][]const u8 = @splat(""); for (all, &spellings) |fmt, *spelling| spelling.* = fmt.pattern(); break :blk spellings; }; pub fn pattern(self: Format) []const u8 { return switch (self) { .iso => "YYYY-MM-DD", .dotted => "DD.MM.YYYY", .dotted_short => "DD.MM.YY", }; } }; pub fn isSame(self: Date, other: anytype) bool { return self.year == other.year and self.month == other.month and self.day == other.day; } fn digitsOf(T: type, text: []const u8) ?T { var value: T = 0; for (text) |c| { if (c < '0' or c > '9') return null; value = value * 10 + (c - '0'); } return value; } fn daysInMonth(year: u16, month: u8) u8 { return switch (month) { 1, 3, 5, 7, 8, 10, 12 => 31, 4, 6, 9, 11 => 30, 2 => if (isLeapYear(year)) 29 else 28, else => 0, }; } /// The Gregorian rule, not the divisible-by-four approximation. fn isLeapYear(year: u16) bool { if (year % 400 == 0) return true; if (year % 100 == 0) return false; return year % 4 == 0; } pub fn parse(cell: []const u8, fmt: Format) ?Date { if (cell.len != fmt.pattern().len) return null; // zlinter-disable no_unsafe_undefined - It is set correctly below var year: u16 = undefined; var month: u8 = undefined; var day: u8 = undefined; // zlinter-disable no_unsafe_undefined switch (fmt) { .iso => { if (cell[4] != '-' or cell[7] != '-') return null; year = digitsOf(u16, cell[0..4]) orelse return null; month = digitsOf(u8, cell[5..7]) orelse return null; day = digitsOf(u8, cell[8..10]) orelse return null; }, .dotted, .dotted_short => { if (cell[2] != '.' or cell[5] != '.') return null; day = digitsOf(u8, cell[0..2]) orelse return null; month = digitsOf(u8, cell[3..5]) orelse return null; year = digitsOf(u16, cell[6..]) orelse return null; // M1-CSV-016: a two-digit year is one from 2000 to 2099. if (fmt == .dotted_short) year += 2000; }, } if (month < 1 or month > 12) return null; if (day < 1 or day > daysInMonth(year, month)) return null; return .{ .year = year, .month = month, .day = day }; }