╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ timestamp.zig ────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭ find file ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ ╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │ │ │http│ ssh │ │ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
8 pub fn format(aa: std.mem.Allocator, timestamp: i64, now: i64) !Text { 9 if (timestamp < 0) return .{ .relative = "timestamp unavailable", .exact = "" }; 10 return .{ .relative = try relative(aa, timestamp, now), .exact = try exact(aa, @intCast(timestamp)) }; 11 } 12 13 // show only the largest whole unit; months and years use fixed durations. 14 fn relative(aa: std.mem.Allocator, timestamp: i64, now: i64) ![]const u8 { 15 const future = timestamp > now; 16 const elapsed = @abs(@as(i128, now) - timestamp); 17 if (elapsed == 0) return "just now"; 18 const units = [_]struct { seconds: u64, name: []const u8 }{ 19 .{ .seconds = 365 * std.time.s_per_day, .name = "year" }, 20 .{ .seconds = 30 * std.time.s_per_day, .name = "month" }, 21 .{ .seconds = std.time.s_per_day, .name = "day" }, 22 .{ .seconds = std.time.s_per_hour, .name = "hour" }, 23 .{ .seconds = std.time.s_per_min, .name = "minute" }, 24 .{ .seconds = 1, .name = "second" }, 25 }; 26 for (units) |unit| { 27 if (elapsed < unit.seconds) continue; 28 const count = elapsed / unit.seconds; 29 return aa.print("{s}{d} {s}{s}{s}", .{ if (future) "in " else "", count, unit.name, if (count == 1) "" else "s", if (future) "" else " ago" }); 30 } 31 unreachable; 32 } 33 34 // compact utc, including seconds; z is the utc designator. 35 fn exact(aa: std.mem.Allocator, timestamp: u64) ![]const u8 { 36 const seconds = std.time.epoch.EpochSeconds{ .secs = timestamp }; 37 const year = seconds.getEpochDay().calculateYearDay(); 38 const month = year.calculateMonthDay(); 39 const day = seconds.getDaySeconds(); 40 return aa.print("{d:0>4}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2}:{d:0>2}Z", .{ year.year, month.month.numeric(), month.day_index + 1, day.getHoursIntoDay(), day.getMinutesIntoHour(), day.getSecondsIntoMinute() }); 41 } 42