diff options
| author | 2022-10-02 09:23:04 +0200 | |
|---|---|---|
| committer | 2022-10-02 09:23:04 +0200 | |
| commit | 3161eeb0283f990ba83fbce33d5e3f7f0ad95f24 (patch) | |
| tree | f81b2b4c53141b8cb5177b21c3a1a00d6ed1e820 /xs_time.h | |
| parent | Updated TODO. (diff) | |
| download | penes-snac2-3161eeb0283f990ba83fbce33d5e3f7f0ad95f24.tar.gz penes-snac2-3161eeb0283f990ba83fbce33d5e3f7f0ad95f24.tar.xz penes-snac2-3161eeb0283f990ba83fbce33d5e3f7f0ad95f24.zip | |
Backport from xs.
Diffstat (limited to 'xs_time.h')
| -rw-r--r-- | xs_time.h | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/xs_time.h b/xs_time.h new file mode 100644 index 0000000..ce44cdc --- /dev/null +++ b/xs_time.h | |||
| @@ -0,0 +1,58 @@ | |||
| 1 | /* copyright (c) 2022 grunfink - MIT license */ | ||
| 2 | |||
| 3 | #ifndef _XS_TIME_H | ||
| 4 | |||
| 5 | #define _XS_TIME_H | ||
| 6 | |||
| 7 | #include <time.h> | ||
| 8 | |||
| 9 | d_char *xs_str_time(time_t t, const char *fmt, int local); | ||
| 10 | #define xs_str_localtime(t, fmt) xs_str_time(t, fmt, 1) | ||
| 11 | #define xs_str_utctime(t, fmt) xs_str_time(t, fmt, 0) | ||
| 12 | time_t xs_parse_time(const char *str, const char *fmt, int local); | ||
| 13 | #define xs_parse_localtime(str, fmt) xs_parse_time(str, fmt, 1) | ||
| 14 | #define xs_parse_utctime(str, fmt) xs_parse_time(str, fmt, 0) | ||
| 15 | |||
| 16 | #ifdef XS_IMPLEMENTATION | ||
| 17 | |||
| 18 | d_char *xs_str_time(time_t t, const char *fmt, int local) | ||
| 19 | /* returns a d_char with a formated time */ | ||
| 20 | { | ||
| 21 | struct tm tm; | ||
| 22 | char tmp[64]; | ||
| 23 | |||
| 24 | if (t == 0) | ||
| 25 | t = time(NULL); | ||
| 26 | |||
| 27 | if (local) | ||
| 28 | localtime_r(&t, &tm); | ||
| 29 | else | ||
| 30 | gmtime_r(&t, &tm); | ||
| 31 | |||
| 32 | strftime(tmp, sizeof(tmp), fmt, &tm); | ||
| 33 | |||
| 34 | // printf("%d %d\n", local, t - xs_parse_time(tmp, fmt, local)); | ||
| 35 | |||
| 36 | return xs_str_new(tmp); | ||
| 37 | } | ||
| 38 | |||
| 39 | |||
| 40 | char *strptime(const char *s, const char *format, struct tm *tm); | ||
| 41 | |||
| 42 | time_t xs_parse_time(const char *str, const char *fmt, int local) | ||
| 43 | { | ||
| 44 | struct tm tm; | ||
| 45 | |||
| 46 | memset(&tm, '\0', sizeof(tm)); | ||
| 47 | strptime(str, fmt, &tm); | ||
| 48 | |||
| 49 | if (local) | ||
| 50 | tm.tm_isdst = -1; | ||
| 51 | |||
| 52 | return local ? mktime(&tm) : timegm(&tm); | ||
| 53 | } | ||
| 54 | |||
| 55 | |||
| 56 | #endif /* XS_IMPLEMENTATION */ | ||
| 57 | |||
| 58 | #endif /* _XS_TIME_H */ | ||