Skip to content

Commit

Permalink
fmt/time: add fmt_timestamp_us
Browse files Browse the repository at this point in the history
  • Loading branch information
sreimers committed Feb 7, 2024
1 parent 14a3236 commit 50f153d
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 3 deletions.
1 change: 1 addition & 0 deletions cmake/re-config.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ if(WIN32)
list(APPEND RE_DEFINITIONS
WIN32
_WIN32_WINNT=0x0600
_UCRT
)

unset(CMAKE_EXTRA_INCLUDE_FILES)
Expand Down
7 changes: 4 additions & 3 deletions include/re_fmt.h
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,10 @@ static inline bool str_isset(const char *s)


/* time */
int fmt_gmtime(struct re_printf *pf, void *ts);
int fmt_timestamp(struct re_printf *pf, void *ts);
int fmt_human_time(struct re_printf *pf, const uint32_t *seconds);
int fmt_gmtime(struct re_printf *pf, void *ts);
int fmt_timestamp(struct re_printf *pf, void *ts);
int fmt_timestamp_us(struct re_printf *pf, void *arg);
int fmt_human_time(struct re_printf *pf, const uint32_t *seconds);


void hexdump(FILE *f, const void *p, size_t len);
Expand Down
40 changes: 40 additions & 0 deletions src/fmt/time.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
* Copyright (C) 2010 Creytiv.com
*/

#ifdef __MINGW32__
#define _POSIX_C_SOURCE
#endif

#include <time.h>

#ifdef WIN32
Expand Down Expand Up @@ -129,3 +133,39 @@ int fmt_timestamp(struct re_printf *pf, void *arg)

return re_hprintf(pf, "%02u:%02u:%02u.%03llu", h, m, s, ms);
}


/**
* Print local time stamp including microseconds relative to user's timezone
*
* @param pf Print function for output
* @param arg Not used
*
* @return 0 if success, otherwise errorcode
*/
int fmt_timestamp_us(struct re_printf *pf, void *arg)
{
int h, m, s;
uint64_t us;
struct timespec tspec;
struct tm tm;

#if defined(WIN32) && !defined(__MINGW32__)
timespec_get(&tspec, TIME_UTC);
int err = localtime_s(&tm, &tspec.tv_sec);
if (err)
return err;
#else
(void)clock_gettime(CLOCK_REALTIME, &tspec);
if (!localtime_r(&tspec.tv_sec, &tm))
return EINVAL;
#endif

h = tm.tm_hour;
m = tm.tm_min;
s = tm.tm_sec;
us = tspec.tv_nsec / 1000;
(void)arg;

return re_hprintf(pf, "%02u:%02u:%02u.%06llu", h, m, s, us);
}

0 comments on commit 50f153d

Please sign in to comment.