Something went wrong. Try again.
A basic datetime module in zig
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364const std = @import("std");
const Self = @This();
gpa: std.mem.Allocator,tz: std.tz.Tz,
/// Load timezone data.pub fn loadTz(gpa: std.mem.Allocator, io: std.Io, environ_map: ?*std.process.Environ.Map) !Self { if (environ_map) |e| { if (e.get("TZ")) |tzname| { var dir = try std.Io.Dir.openDirAbsolute(io, "/usr/share/zoneinfo", .{ .access_sub_paths = true }); defer dir.close(io); var tzfile = try dir.openFile(io, tzname, .{}); defer tzfile.close(io); var buf: [256]u8 = undefined; var reader = tzfile.reader(io, &buf); const tz = try std.tz.Tz.parse(gpa, &reader.interface); return .{ .gpa = gpa, .tz = tz }; } }
var cwd = std.Io.Dir.cwd(); var tzfile = try cwd.openFile(io, "/etc/localtime", .{}); defer tzfile.close(io); var buf: [256]u8 = undefined; var reader = tzfile.reader(io, &buf); const tz = try std.tz.Tz.parse(gpa, &reader.interface); return .{ .gpa = gpa, .tz = tz };}
pub fn deinit(self: *Self) void { self.tz.deinit();}
pub fn getOffset(self: Self, timestamp: std.Io.Timestamp) ?*std.tz.Timetype { const seconds = timestamp.toSeconds(); for (0.., self.tz.transitions) |index, transition| { if (transition.ts < seconds) continue; return self.tz.transitions[index - 1].timetype; }
return null;}
test loadTz { const NanoMultiplier: i128 = 1000000000; const realTimestamp = std.Io.Timestamp.now(std.testing.io, .real); const epoch: i64 = @intCast(@divFloor(realTimestamp.nanoseconds, NanoMultiplier)); try std.testing.expect(epoch > 0); const tz_ = try loadTz(std.testing.allocator, std.testing.io, null); var tz = tz_.tz; defer tz.deinit(); if (tz.footer) |footer| { try std.testing.expect(footer.len > 0); } var index: usize = 0; while ((index + 1) < tz.transitions.len and tz.transitions[index + 1].ts < epoch) { index += 1; } try std.testing.expect(index < tz.transitions.len);}