Created
August 30, 2018 13:43
-
-
Save larsch/3c27bc24fdd82d9981da098f84545884 to your computer and use it in GitHub Desktop.
Minimal function to format current time according to ISO8601 with milliseconds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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