Stack Exchange
Calculating the difference between two ISO 8601 dates (that include milliseconds) in C
I have two ISO 8601 formatted dates:
20170423T221118.585Z
20170423T221119.583Z
On Linux in C using core language libraries how do I calculate the difference in milliseconds between these two dates ?

Using the core C language do the following:
#include <stdio.h>
#include <time.h>

double subtract_dates(const char *start_date_time, const char *end_date_time);
void create_tm(time_t *ret_time, const char* date_time, int *ret_time_ms);

int main(int argc, char *argv[])
{
    const char *start_date_time = "20170423T221118.585Z";
    const char *end_date_time = "20170423T221119.583Z";
    double msdiff;

    msdiff = subtract_dates(end_date_time, start_date_time);

    printf("Date/time difference(ms) = %f\n", msdiff);
}

double subtract_dates(const char *end_date_time, const char *start_date_time )
{
    time_t ret_start_date_time;
    time_t ret_end_date_time;
    double diff_s;
    int start_time_ms;
    int end_time_ms;
    double diff_ms;

    create_tm(&ret_start_date_time, start_date_time, &start_time_ms);
    create_tm(&ret_end_date_time, end_date_time, &end_time_ms);

    diff_s = difftime(ret_end_date_time, ret_start_date_time);

    // convert to milliseconds
    diff_ms = (diff_s * 1000) + (end_time_ms - start_time_ms);

    return diff_ms;
}

void create_tm(time_t *ret_time, const char* date_time, int *ret_time_ms)
{
    struct tm time;
    time_t otherTime;
    int y,M,d,h,m,s;
    int ms;

    sscanf(date_time, "%4d%2d%2dT%2d%2d%2d.%3dZ", &y, &M, &d, &h, &m, &s, &ms);

    time.tm_year = y - 1900; // Year since 1900
    time.tm_mon = M - 1;     // 0-11
    time.tm_mday = d;        // 1-31
    time.tm_hour = h;        // 0-23
    time.tm_min = m;         // 0-59
    time.tm_sec = s;         // 0-61 (0-60 in C++11)
    time.tm_isdst = -1;      // let mktime check for DST

    *ret_time = mktime(&time);
    *ret_time_ms = ms;
}

This will give you the following output:
Date/time difference(ms) = 998.000000

Important: missing time.tm_isdst = something; setting.  Suggest -1.  Some details: Checking the result of sscanf() is important here. With the current format, certainty of the final Z is not tested.  ISO 8601 Year is not necessarily limited to 4 digits.  Using int for int subtract_dates() can easliy overflow - maybe long long or just use the double of difftime().
