From 274ca939e0a5baa74d4ff61518ed0af7b0da5465 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=A9mie=20Galarneau?= Date: Fri, 17 May 2019 16:03:25 -0400 Subject: [PATCH] Add a time_to_iso8601_str() utility MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit time_to_iso8601_str() formats a Unix timestamp to an ISO 8601 compatible string. For now, the only ISO 8601 time format used in LTTng-tools is the "YYYYmmddTHHMMSS+HHMM" form used by the session rotation feature. Since ISO 8601 allows many formats, this functions may need to be renamed at some point. Signed-off-by: Jérémie Galarneau --- src/common/time.c | 33 +++++++++++++++++++++++++++++++++ src/common/time.h | 12 ++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/common/time.c b/src/common/time.c index a01c16df5..885f58cb1 100644 --- a/src/common/time.c +++ b/src/common/time.c @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -80,3 +81,35 @@ void __attribute__((constructor)) init_locale_utf8_support(void) utf8_output_supported = true; } } + +LTTNG_HIDDEN +int time_to_iso8601_str(time_t time, char *str, size_t len) +{ + int ret = 0; + struct tm *tm_result; + struct tm tm_storage; + size_t strf_ret; + + if (len < ISO8601_STR_LEN) { + ERR("Buffer too short to format ISO 8601 timestamp: %zu bytes provided when at least %zu are needed", + len, ISO8601_STR_LEN); + ret = -1; + goto end; + } + + tm_result = localtime_r(&time, &tm_storage); + if (!tm_result) { + ret = -1; + PERROR("Failed to break down timestamp to tm structure"); + goto end; + } + + strf_ret = strftime(str, len, "%Y%m%dT%H%M%S%z", tm_result); + if (strf_ret == 0) { + ret = -1; + ERR("Failed to format timestamp as local time"); + goto end; + } +end: + return ret; +} diff --git a/src/common/time.h b/src/common/time.h index 24513d30b..dc07633e9 100644 --- a/src/common/time.h +++ b/src/common/time.h @@ -36,6 +36,8 @@ #define USEC_PER_MINUTE (USEC_PER_SEC * SEC_PER_MINUTE) #define USEC_PER_HOURS (USEC_PER_MINUTE * MINUTE_PER_HOUR) +#define ISO8601_STR_LEN sizeof("YYYYmmddTHHMMSS+HHMM") + LTTNG_HIDDEN bool locale_supports_utf8(void); @@ -61,4 +63,14 @@ int timespec_to_ms(struct timespec ts, unsigned long *ms); LTTNG_HIDDEN struct timespec timespec_abs_diff(struct timespec ts_a, struct timespec ts_b); +/* + * Format a Unix timestamp to an ISO 8601 compatible timestamp of + * the form "YYYYmmddTHHMMSS+HHMM" in local time. `len` must >= to + * ISO8601_STR_LEN. + * + * Returns 0 on success, else -1 on error. + */ +LTTNG_HIDDEN +int time_to_iso8601_str(time_t time, char *str, size_t len); + #endif /* LTTNG_TIME_H */ -- 2.34.1