diff options
author | default <nobody@localhost> | 2022-10-02 09:23:04 +0200 |
---|---|---|
committer | default <nobody@localhost> | 2022-10-02 09:23:04 +0200 |
commit | 3161eeb0283f990ba83fbce33d5e3f7f0ad95f24 (patch) | |
tree | f81b2b4c53141b8cb5177b21c3a1a00d6ed1e820 | |
parent | 432067805ece3df29be7fe16e73f475b72c68038 (diff) |
Backport from xs.
-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 @@ +/* copyright (c) 2022 grunfink - MIT license */ + +#ifndef _XS_TIME_H + +#define _XS_TIME_H + +#include <time.h> + +d_char *xs_str_time(time_t t, const char *fmt, int local); +#define xs_str_localtime(t, fmt) xs_str_time(t, fmt, 1) +#define xs_str_utctime(t, fmt) xs_str_time(t, fmt, 0) +time_t xs_parse_time(const char *str, const char *fmt, int local); +#define xs_parse_localtime(str, fmt) xs_parse_time(str, fmt, 1) +#define xs_parse_utctime(str, fmt) xs_parse_time(str, fmt, 0) + +#ifdef XS_IMPLEMENTATION + +d_char *xs_str_time(time_t t, const char *fmt, int local) +/* returns a d_char with a formated time */ +{ + struct tm tm; + char tmp[64]; + + if (t == 0) + t = time(NULL); + + if (local) + localtime_r(&t, &tm); + else + gmtime_r(&t, &tm); + + strftime(tmp, sizeof(tmp), fmt, &tm); + +// printf("%d %d\n", local, t - xs_parse_time(tmp, fmt, local)); + + return xs_str_new(tmp); +} + + +char *strptime(const char *s, const char *format, struct tm *tm); + +time_t xs_parse_time(const char *str, const char *fmt, int local) +{ + struct tm tm; + + memset(&tm, '\0', sizeof(tm)); + strptime(str, fmt, &tm); + + if (local) + tm.tm_isdst = -1; + + return local ? mktime(&tm) : timegm(&tm); +} + + +#endif /* XS_IMPLEMENTATION */ + +#endif /* _XS_TIME_H */ |