summaryrefslogtreecommitdiff
path: root/xs_time.h
diff options
context:
space:
mode:
Diffstat (limited to 'xs_time.h')
-rw-r--r--xs_time.h58
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
9d_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)
12time_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
18d_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
40char *strptime(const char *s, const char *format, struct tm *tm);
41
42time_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 */