aboutsummaryrefslogtreecommitdiff
path: root/lib/time/time_defs.h
blob: eac3f23a94606524af4c6f4d7cc025c2f6383908 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Some helper logic for working with times.

#pragma once
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

typedef struct timeval Time;

static OptionalText_t _local_timezone = NONE_TEXT;

static INLINE Text_t num_format(long n, const char *unit) {
    if (n == 0) return Text("now");
    return Text$from_str(
        String((int64_t)labs(n), " ", unit, (n == -1 || n == 1) ? "" : "s", n <= 0 ? " ago" : " later"));
}

static void set_local_timezone(Text_t tz) {
    setenv("TZ", Text$as_c_string(tz), 1);
    _local_timezone = tz;
    tzset();
}

#define WITH_TIMEZONE(tz, body)                                                                                        \
    ({                                                                                                                 \
        if (tz.length >= 0) {                                                                                          \
            OptionalText_t old_timezone = _local_timezone;                                                             \
            set_local_timezone(tz);                                                                                    \
            body;                                                                                                      \
            set_local_timezone(old_timezone);                                                                          \
        } else {                                                                                                       \
            body;                                                                                                      \
        }                                                                                                              \
    })