Time and Date

One area where the Zig standard library is currently lacking is time and date. Let’s try using C functions instead.

time.h declares functions related to date and time:

#include <time.h>
const std = @import("std");
const print = std.debug.print;
const c = @import("c");

pub fn main() void {
    // time returns the current time in Unix time.
    const t = c.time(null);

    // localtime converts that to a struct with year,
    // month, and so on. It returns a pointer to static
    // memory; best to copy it to a local variable.
    const tm_pointer = c.localtime(&t);
    const tm = tm_pointer.*;

    // Convert the values to Zig types, then print them.
    const year: u64 = @intCast(1900 + tm.tm_year);
    const month: u64 = @intCast(tm.tm_mon + 1);
    const day: u64 = @intCast(tm.tm_mday);
    const hour: u64 = @intCast(tm.tm_hour);
    const min: u64 = @intCast(tm.tm_min);
    const sec: u64 = @intCast(tm.tm_sec);
    print(
        "{d:04}-{d:02}-{d:02} {d:02}:{d:02}:{d:02}\n",
        .{ year, month, day, hour, min, sec },
    );
}

build.zig is very similar to the one in Using C:

const std = @import("std");

pub fn build(b: *std.Build) void {
    const root_source_file = b.path("time.zig");

    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const translate_c = b.addTranslateC(.{
        .root_source_file = b.path("time.h"),
        .target = target,
        .optimize = optimize,
    });
    const c_module = translate_c.createModule();

    const exe = b.addExecutable(.{
        .name = "time",
        .root_module = b.createModule(.{
            .root_source_file = root_source_file,
            .target = target,
            .optimize = optimize,
            .imports = &.{
                .{
                    .name = "c",
                    .module = c_module,
                },
            },
        }),
    });
    b.installArtifact(exe);

    const run_step = b.step("run", "Run the program");
    const run_exe = b.addRunArtifact(exe);
    run_step.dependOn(&run_exe.step);
}
$ zig build run
2026-07-17 13:24:58

This is the last example for now. More will be added soon!