如何在 Zig 中以
Sun Sep 15 10:01:02 AM CEST 2024
格式显示时间和日期?
PS:刚开始学习Zig
这是第 3 方库 zdt 和 zeit 的示例。由于OP隐式询问时区(“CEST”),因此我将示例限制为处理这些时区的库。免责声明:我是其中之一的作者,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});
// -----------------------------------------------------------------------
}
备注: