ctimec-libraries

Get milliseconds difference from time and date string values in C


I have two date and time strings separately in variables. I need to calculate the difference between these 2 date and time values in milliseconds. How to get that in C. The solution should work across platforms(at least windows and unix).

char date1[] = {"26/11/2015"};
char time1[] = {"20:22:19"};
char date2[] = {"26/11/2015"};
char time2[] = {"20:23:19"};

First I need to save this into some time structure and then compare 2 time structures to get the difference. What is the time structure which is available in C Library to do this.


Solution

  • Use mktime() and difftime()

    The mktime function returns the specified calendar time encoded as a value of type time_t. If the calendar time cannot be represented, the function returns the value (time_t)(-1). C11dr §7.27.2.3 4

    The difftime function returns the difference expressed in seconds as a double §7.27.2.2 2

    #include <time.h>
    #include <stdlib.h>
    #include <string.h>
    
    time_t parse_dt(const char *mdy, const char *hms) {
      struct tm tm;
      memset(&tm, 0, sizeof tm);
      if (3 != sscanf(mdy, "%d/%d/%d", &tm.tm_mon, &tm.tm_mday, &tm.tm_year)) return -1;
      tm.tm_year -= 1900;
      tm.tm_mday++;
      if (3 != sscanf(hms, "%d:%d:%d", &tm.tm_hour, &tm.tm_min, &tm.tm_sec)) return -1;
      tm.tm_isdst = -1;  // Assume local time
      return mktime(&tm);
    }
    
    int main() {
      // application
      char date1[] = { "26/11/2015" };
      char time1[] = { "20:22:19" };
      char date2[] = { "26/11/2015" };
      char time2[] = { "20:23:19" };
      time_t t1 = parse_dt(date1, time1);
      time_t t2 = parse_dt(date2, time2);
      if (t1 == -1 || t2 == -1) return 1;
      printf("Time difference %.3f\n", difftime(t2, t1) * 1000.0);
      return 0;
    }
    

    Output

    Time difference 60000.000