I'm attempting to put together an RFC3339 timestamp which will be used to write a certain entry to a database. That would be formatted as, for example, 2004-10-19 10:23:54+02, where the +02 is the offset in hours from GMT. It's this offset which is proving troublesome - I can't seem to derive this value in C.
Here is the code I'm using. When I try to build, it says the tm struct doesn't have a member named tm_gmtoff:
#include <time.h>
#include <stdio.h>
int main(void)
{
time_t now = time(NULL);
struct tm *tm;
int off_sign;
int off;
if ((tm = localtime(&now)) == NULL) {
return -1;
}
off_sign = '+';
off = (int) tm->tm_gmtoff;
if (tm->tm_gmtoff < 0) {
off_sign = '-';
off = -off;
}
printf("%d-%d-%dT%02d:%02d:%02d%c%02d:%02d",
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec,
off_sign, off / 3600, off % 3600);
return 0;
}
If a string is the goal, the easy solution is to use
strftime()
.Output
The
tm_gmtoff
is an optional extra member ofstruct tm
. When available, that or some other similar implementation dependent member would be good to use.With access to
strftime()
and"%z"
, as suggeted by @jwdonahue."%z"
available since C99.Output for CT
Lacking the above choices, code can deduce the timezone offset directly from
localtime()
andgmttime()
: do astruct tm
subtraction.The below takes advantage that a difference in timestamps does not exceed 1 day near January 1st.
Sample output for CT
To print the timezone offset per RFC3339 given
hour, minute
:See also What's the difference between ISO 8601 and RFC 3339 Date Formats?