Skip to content

Instantly share code, notes, and snippets.

@larsch
Created August 30, 2018 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larsch/3c27bc24fdd82d9981da098f84545884 to your computer and use it in GitHub Desktop.
Save larsch/3c27bc24fdd82d9981da098f84545884 to your computer and use it in GitHub Desktop.
Minimal function to format current time according to ISO8601 with milliseconds
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
int iso8601_time(char* buf, size_t size)
{
struct timespec ts;
struct tm tm_local;
struct tm tm_gm;
clock_gettime(CLOCK_REALTIME, &ts);
localtime_r(&ts.tv_sec, &tm_local);
gmtime_r(&ts.tv_sec, &tm_gm);
/* Format date and time */
size_t len = strftime(buf, size, "%FT%T", &tm_gm);
if (len == 0)
return 0;
/* Format fraction of second */
size_t remaining = size - len;
size_t added = snprintf(buf + len, remaining, ".%03lu", ts.tv_nsec / 1000000);
if (added >= remaining)
return 0;
len += added;
/* Format timezone offset */
int tz_offset = (tm_local.tm_hour - tm_gm.tm_hour) * 60 + (tm_local.tm_min - tm_gm.tm_min);
if (tz_offset) {
char sign = tz_offset < 0 ? '-' : '+';
int hours = (int)(abs(tz_offset)) / 60;
int minutes = (int)(abs(tz_offset)) % 60;
remaining = size - len;
added = snprintf(buf + strlen(buf), remaining, "%c%02d:%02d", sign, hours, minutes);
if (added >= remaining)
return 0;
len += added;
} else {
remaining = size - len;
if (remaining < 2)
return 0;
strcpy(buf + len, "Z");
len += 2;
}
return len;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment