Skip to content

Instantly share code, notes, and snippets.

@softprops
Last active March 19, 2024 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save softprops/23d55bb8b4869adc942216e43ff3d60d to your computer and use it in GitHub Desktop.
Save softprops/23d55bb8b4869adc942216e43ff3d60d to your computer and use it in GitHub Desktop.
// remix of https://discordapp.com/channels/605571803288698900/1219282855679496243/1219706356718632981
const std = @import("std");
const Timestamp = struct {
seconds: i64,
pub fn format(
self: @This(),
comptime _: []const u8,
_: std.fmt.FormatOptions,
writer: anytype,
) !void {
const epoch_seconds: std.time.epoch.EpochSeconds = .{ .secs = @intCast(self.seconds) };
const epoch_day = epoch_seconds.getEpochDay();
const day_seconds = epoch_seconds.getDaySeconds();
const year_day = epoch_day.calculateYearDay();
const month_day = year_day.calculateMonthDay();
try writer.print("{d}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}Z", .{
year_day.year,
month_day.month.numeric(),
month_day.day_index,
day_seconds.getHoursIntoDay(),
day_seconds.getMinutesIntoHour(),
day_seconds.getSecondsIntoMinute(),
});
}
};
test "fmt" {
const allocator = std.testing.allocator;
const ts = Timestamp{ .seconds = 1710883557 }; // std.time.timestamp()
const actual = try std.fmt.allocPrint(
allocator,
"{any}",
.{ts},
);
defer allocator.free(actual);
try std.testing.expectEqualStrings(
"2024-03-18T21:25:57Z",
actual,
);
}
pub fn main() !void {
std.debug.print("{any}", .{Timestamp{ .seconds = std.time.timestamp() }});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment