snac2/xs_time.h

111 lines
2.3 KiB
C
Raw Normal View History

2024-01-04 11:22:03 +03:00
/* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
2022-10-02 10:23:04 +03:00
#ifndef _XS_TIME_H
#define _XS_TIME_H
#include <time.h>
2023-01-28 19:49:02 +03:00
xs_str *xs_str_time(time_t t, const char *fmt, int local);
2022-10-02 10:23:04 +03:00
#define xs_str_localtime(t, fmt) xs_str_time(t, fmt, 1)
#define xs_str_utctime(t, fmt) xs_str_time(t, fmt, 0)
2023-06-27 17:52:29 +03:00
time_t xs_parse_iso_date(const char *iso_date, int local);
2022-10-02 10:23:04 +03:00
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)
2023-05-08 10:30:26 +03:00
xs_str *xs_str_time_diff(time_t time_diff);
2022-10-02 10:23:04 +03:00
#ifdef XS_IMPLEMENTATION
2023-01-28 19:49:02 +03:00
xs_str *xs_str_time(time_t t, const char *fmt, int local)
/* returns a string with a formated time */
2022-10-02 10:23:04 +03:00
{
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);
return xs_str_new(tmp);
}
2023-05-08 10:30:26 +03:00
xs_str *xs_str_time_diff(time_t time_diff)
/* returns time_diff in seconds to 'human' units (d:hh:mm:ss) */
{
int secs = time_diff % 60;
int mins = (time_diff /= 60) % 60;
int hours = (time_diff /= 60) % 24;
int days = (time_diff /= 24);
return xs_fmt("%d:%02d:%02d:%02d", days, hours, mins, secs);
}
2022-10-02 10:23:04 +03:00
char *strptime(const char *s, const char *format, struct tm *tm);
time_t xs_parse_time(const char *str, const char *fmt, int local)
{
2023-06-27 17:52:29 +03:00
time_t t = 0;
#ifndef WITHOUT_STRPTIME
struct tm tm = {0};
2022-10-02 10:23:04 +03:00
strptime(str, fmt, &tm);
2022-10-04 19:46:12 +03:00
/* try to guess the Daylight Saving Time */
2022-10-02 10:23:04 +03:00
if (local)
tm.tm_isdst = -1;
2023-06-27 17:52:29 +03:00
t = local ? mktime(&tm) : timegm(&tm);
#endif /* WITHOUT_STRPTIME */
return t;
}
time_t xs_parse_iso_date(const char *iso_date, int local)
/* parses a YYYY-MM-DDTHH:MM:SS date string */
{
time_t t = 0;
#ifndef WITHOUT_STRPTIME
t = xs_parse_time(iso_date, "%Y-%m-%dT%H:%M:%S", local);
#else /* WITHOUT_STRPTIME */
struct tm tm = {0};
if (sscanf(iso_date, "%d-%d-%dT%d:%d:%d",
&tm.tm_year, &tm.tm_mon, &tm.tm_mday,
&tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6) {
tm.tm_year -= 1900;
tm.tm_mon -= 1;
if (local)
tm.tm_isdst = -1;
t = local ? mktime(&tm) : timegm(&tm);
}
#endif /* WITHOUT_STRPTIME */
return t;
2022-10-02 10:23:04 +03:00
}
#endif /* XS_IMPLEMENTATION */
#endif /* _XS_TIME_H */