How can you display the time and date in Sun Sep 15 10:01:02 AM CEST 2024
format in Zig?
PS: just started learn Zig
1
Here’s an example with 3rd party libraries, zdt and zeit. Since the OP implicitly asks about timezones (“CEST”), I limit the example to libraries that handle those. Disclaimer: I’m the author of one of them, zdt.
const std = @import("std");
const zdt = @import("zdt"); // uses: commit 16ed4b7380be285f92fa57c1722a4fb8049bfa87
const zeit = @import("zeit"); // uses: tagged version 0.4.3
pub fn main() !void {
// timezone rule files vary in size, so we need memory from an allocator:
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// for string output:
var formatted = std.ArrayList(u8).init(allocator);
defer formatted.deinit();
// zdt
// -----------------------------------------------------------------------
var dt_zdt = try zdt.Datetime.nowLocal(allocator);
defer dt_zdt.tzDeinit();
try dt_zdt.strftime(formatted.writer(), "%a %b %d %I:%M:%S %p %Z %Y");
std.debug.print("zdt: {s}n", .{formatted.items});
// -----------------------------------------------------------------------
formatted.clearAndFree();
// zeit
// -----------------------------------------------------------------------
const now = try zeit.instant(.{});
const local = try zeit.local(allocator, null);
defer local.deinit();
const now_local = now.in(&local);
const dt_zeit = now_local.time();
try dt_zeit.strftime(formatted.writer(), "%a %b %d %I:%M:%S %p %Z %Y");
std.debug.print("zeit: {s}n", .{formatted.items});
// -----------------------------------------------------------------------
}
Notes:
- for pure date/time, there are other libraries out there as well
- also note that you’ll need to tell the build system where and which version (commit, tag etc.) of the libraries to fetch in a
.zon
file and thebuild.zig
- helpful in this context: Build System Tricks on ziggit.dev
- you could also use C libraries, which can be integrated very well with Zig