79113
Ma
mini-coding-agent / files
mini-coding-agent / src / time.zig
1.9 KB
1const std = @import("std"); 2const platform = @import("platform.zig"); 3 4pub fn nowMs() i64 { 5 return std.Io.Timestamp.now(platform.io, .real).toMilliseconds(); 6} 7 8const Date = struct { 9 year: u16, 10 month: u8, 11 day: u8, 12 hour: u8, 13 minute: u8, 14 second: u8, 15 milli: u64, 16 17 fn fromMs(ms: i64) Date { 18 const epoch = std.time.epoch.EpochSeconds{ .secs = @intCast(@divFloor(ms, 1000)) }; 19 const ymd = epoch.getEpochDay().calculateYearDay(); 20 const md = ymd.calculateMonthDay(); 21 const ds = epoch.getDaySeconds(); 22 return .{ 23 .year = ymd.year, 24 .month = md.month.numeric(), 25 .day = md.day_index + 1, 26 .hour = ds.getHoursIntoDay(), 27 .minute = ds.getMinutesIntoHour(), 28 .second = ds.getSecondsIntoMinute(), 29 .milli = @intCast(@mod(ms, 1000)), 30 }; 31 } 32}; 33 34fn isoFromMs(buf: []u8, ms: i64) []const u8 { 35 const d = Date.fromMs(ms); 36 return std.fmt.bufPrint(buf, "{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}Z", .{ 37 d.year, d.month, d.day, d.hour, d.minute, d.second, d.milli, 38 }) catch unreachable; 39} 40 41pub fn humanize(buf: []u8, ms: i64) []const u8 { 42 const total = @max(0, @divFloor(ms, 1000)); 43 const s = @mod(total, 60); 44 const m = @mod(@divFloor(total, 60), 60); 45 const h = @divFloor(total, 3600); 46 if (h > 0) return std.fmt.bufPrint(buf, "{d}h {d}m {d}s", .{ h, m, s }) catch ""; 47 if (m > 0) return std.fmt.bufPrint(buf, "{d}m {d}s", .{ m, s }) catch ""; 48 return std.fmt.bufPrint(buf, "{d}s", .{s}) catch ""; 49} 50 51pub fn isoAlloc(a: std.mem.Allocator) []const u8 { 52 const buf = a.alloc(u8, 32) catch unreachable; 53 return isoFromMs(buf, nowMs()); 54} 55 56pub fn stamp(buf: []u8, ms: i64) []const u8 { 57 const d = Date.fromMs(ms); 58 return std.fmt.bufPrint(buf, "{d:0>4}{d:0>2}{d:0>2}-{d:0>2}{d:0>2}{d:0>2}", .{ 59 d.year, d.month, d.day, d.hour, d.minute, d.second, 60 }) catch unreachable; 61}