diff --git a/src/utils/utils.c b/src/utils/utils.c index f8dbdbf39f3ade3644706bd4084c946de66361d9..14468f66a253d219aed083ad549508e3a8bf96f5 100644 --- a/src/utils/utils.c +++ b/src/utils/utils.c @@ -10,6 +10,7 @@ #include <stdio.h> #include <string.h> #include <signal.h> +#define __USE_XOPEN #include <time.h> #include <unistd.h> #include <sys/types.h> @@ -158,6 +159,7 @@ uint32_t timestamp_elapsed_sec(struct timespec *ts) if (ts->tv_sec == 0) return -1; + /* seconds and nanoseconds since the Epoch */ if (clock_gettime(CLOCK_REALTIME, &now) < 0) now.tv_sec = 0; @@ -172,6 +174,7 @@ int timestamp_expired(struct timespec *a, unsigned int tmo_ms) struct timespec now; unsigned long diff_ns = 0, diff_s = 0; + /* seconds and nanoseconds since the Epoch */ if (clock_gettime(CLOCK_REALTIME, &now) < 0) return -1; @@ -218,6 +221,55 @@ char *time_to_timestamp(time_t *t, char *tsp) return tsp; } +time_t timestamp_to_time(const char *tsp) +{ + struct tm tm_time; + char *tzone; + time_t res; + long int toff, sign; + int toff_hour, toff_min; + + /* Example timestamp: "2019-02-11T06:42:31-08:00" */ + memset(&tm_time, 0, sizeof(tm_time)); + strptime(tsp, "%Y-%m-%dT%H:%M:%S", &tm_time); + + tzset(); + res = mktime(&tm_time); + + tzone = strchr(tsp, '+'); + if (!tzone) { + tzone = strchr(tsp, '-'); + sign = -1L; + } else { + sign = +1L; + } + + if (tzone) { + sscanf(tzone+1, "%02d:%02d", &toff_hour, &toff_min); + toff = toff_hour * 3600 + toff_min * 60; // seconds + toff *= -sign; + res += toff; + } + + return res; +} + +struct timespec time_to_timespec(time_t t) +{ + struct timespec res = {}; + + res.tv_sec = t; + res.tv_nsec = 0; + + return res; +} + +struct timespec tsp_to_timespec(const char *tsp) +{ + return time_to_timespec(timestamp_to_time(tsp)); +} + + /** list utility functions */ /** * list_num_entries - gets number of entries on the list diff --git a/src/utils/utils.h b/src/utils/utils.h index 4299b21d2dd561e7182f2c6340d1d8de3b45023b..9de337fa842674097a1e715d281c641c845e8561 100644 --- a/src/utils/utils.h +++ b/src/utils/utils.h @@ -67,6 +67,9 @@ static inline int timestamp_invalid(struct timespec *ts) uint32_t timestamp_elapsed_sec(struct timespec *ts); int timestamp_expired(struct timespec *a, unsigned int tmo_ms); char *time_to_timestamp(time_t *t, char *tsp); +time_t timestamp_to_time(const char *tsp); +struct timespec time_to_timespec(time_t *t); +struct timespec tsp_to_timespec(const char *tsp); /* bytes from-to hexstring helper functions */ int hex2byte(const char *hex);