To calculate the the difference in seconds in C, use difftime()
, it returns the difference expressed in seconds.
double difftime(time_t time1, time_t time0);
If needed, to get the present time, use time()
. It determines the current calendar time.
time_t time(time_t *timer);
So all that is left is how to take strings like "2016-04-10T02:36:00+02:00" into time_t
.
Covert the string into numeric parts.
if (8 == sscanf(buf, "%d-%d-%dT%d:%d:%d%d:%d", &y, &m, ..., &tzh, &tzm)) Success();
Convert the y,m,d ...
into struct tm
struct tm tm = {0}; // Important to first zero fill
tm.tm_year = y - 1900;
tm.tm_mon = m - 1;
tm.tm_mday = d;
...
tm.tm_hour = H + tzh;
tm.tm_min = M + tzm*sign(tzh);
tm.tm_sec = S;
Convert struct tm
(in universal time) to time_t
. This step is hard as C provides no clear standard way to do it. This this a reasonable portable method. See the rest of the post for alternate approaches.
Notice no assumption is made (or needed) about time_t
being seconds since 1970 nor that struct tm
has only 9 fields.