How to get the current (date)time and add one hour to it?

Hello, I’m looking to get the current (date)time and add one hour to it.

Its not clear going through Io.Clock, Io.Duration, Io.Timeout, and Io.Timestamp.

Whats the simplest way to:

const start = // get current time
const end = // add 1 hour to it
print("Start: {any} End: {any}", .{start, end});

?

You need an Io implementation, and only Threaded is reasonably complete at this moment.
The Io interface is changing very rapidly. But as of this second, the way to do it is:

var t: std.Io.Threaded = .init_single_threaded;
const io = t.io();
const now = try io.vtable.now();
const one_hour : std.Io.Duration = .fromSeconds(60 * 60);
const now_plus_one_hour = now.addDuration(one_hour);
2 Likes

You can also use calls to “low level” C functions, at least for now (while these things are being reworked). Not necessarily the best way to do it, but it is always a last resort. So, something like (again, this is C code):

time_t seconds = time(0);
seconds += 1 * 60 * 60;
1 Like

zeit can do that.

const std = @import("std");
const zeit = @import("zeit");

pub fn main() !void {
    const allocator = std.heap.page_allocator;
    var env = try std.process.getEnvMap(allocator);
    defer env.deinit();
    const local = try zeit.local(allocator, &env);

    const now = try zeit.instant(.{});
    const now2 = try now.add(.{
        .hours = 1,
    });
    const time = now2.time();
    var buffer: [100]u8 = undefined;
    var writer = std.Io.Writer.fixed(&buffer);
    try time.strftime(&writer, "%Y-%m-%d %H:%M:%S %Z");
    var buffer2 = buffer[0..writer.end];
    std.debug.print("{s}\n", .{buffer2}); // UTC

    const now3 = now2.in(&local);
    const time2 = now3.time();
    writer = std.Io.Writer.fixed(&buffer);
    try time2.strftime(&writer, "%Y-%m-%d %H:%M:%S %Z");
    buffer2 = buffer[0..writer.end];
    std.debug.print("{s}\n", .{buffer2}); // local
}
1 Like