There is no way to get local time without touching c or 3rd party libs??
Maybe this helps you
std.Io.Clock
But the way I implemented getting localtime was with C:
const ctime = @cImport(@cInclude("time.h"));
fn formatCurrentTime(_: void, w: *std.Io.Writer) !void {
const time = try w.writableSliceGreedy(64);
var now: ctime.time_t = ctime.time(null);
const timeinfo = ctime.localtime(&now);
const fmt = "%b %d %H:%M:%S"; // Example: "Oct 30 12:47:23"
const time_len = ctime.strftime(time.ptr, time.len, fmt, timeinfo);
w.advance(time_len);
}
// Or this:
fn currentTime(buf: []u8) ![]u8 {
var now: ctime.time_t = ctime.time(null);
const timeinfo = ctime.localtime(&now);
const fmt = "%b %d %H:%M:%S"; // Example: "Oct 30 12:47:23"
const len = ctime.strftime(buf.ptr, buf.len, fmt, timeinfo);
if (len == 0) return error.FormatFailed;
return buf[0..len];
}
I’m quite new to programming and Zig also. If there is anyone with a better approach or knows more I’d like to see it as well ![]()
Yea I started implementing this with c but decided to stop. Cannot justify this if I already imported std. 100+ LOC to get a local time string in a conventional format sounds absolutely ridiculous)). Your solution is not thal long, but I am trying to keep this one clean without any C.
The relevant issue is
I have a zig library for this. Feel free to vendor whatever you need and delete what you don’t. GitHub - rockorager/zeit: a date and time library written in zig. Timezone, DST, and leap second aware
Actually there are a couple of approaches in Zig by now, see e.g. GitHub - zigcc/awesome-zig: A collection of some awesome public Zig programming language projects.
What I like about the C approach @charlie is that it offers a handy “bypass” of all the timezone stuff
DATE and TIMESTAMP field management
ended up with this fn
const time = @cImport(@cInclude("time.h"));
fn updateSyncTime(self: *SyncQueue, allocator: std.mem.Allocator) !void {
if (self.sync_time) |old_val| allocator.free(old_val);
var buf: [16]u8 = undefined;
var time_str: time.tm = undefined;
var current_time = time.time(null);
const local = time.localtime_r(¤t_time, &time_str); // C23
const format = "%b %d %H:%M:%S";
const len = time.strftime(&buf, buf.len, format, local);
self.sync_time = try allocator.dupe(
u8,
if (len == 0) "unknown" else buf[0..len],
);
}
you might want to drop deprecated localtime