0

I'm writing a Arduino-script, which is C/C++. One of the key functions of the script, is reading a date from an API and calculate how many seconds are left until that datetime.

A typical value is 2016-04-10T02:36:00+02:00 which seems like a NSDate. I've found lots of solutions to accomplish what I want in Objective-C, but not in C/C++.

Any help would be highly appreciated.

poff
  • 25
  • 5
  • The formula for calculating epoch time from individual time component (year/month/day/hour/minute/second/timezone) is (or should be) a homework assignment in most high school-level computer programming courses. it is not complicated. Sadly this wheel keeps getting reinvented, and I don't know offhand a common library that provides it, but the plain truth is that the stock POSIX API simply sucks for this, unless you need to convert to/from the local system timezone. Just tighten your belt, up one notch, and calculate it yourself. It's not hard. – Sam Varshavchik Apr 10 '16 at 00:43
  • There is no such thing as "C/C++". What language are you _actually_ using? – Lightness Races in Orbit Apr 10 '16 at 00:43
  • @LightnessRacesinOrbit Arduino is a own programming language, and from what I understand you can use both C and C++ inside of it. – poff Apr 10 '16 at 00:49
  • @poff: Yes but you can only write in one language at any given time. Which one is it for you? – Lightness Races in Orbit Apr 10 '16 at 00:52
  • @LightnessRacesinOrbit I'm programming in Arduino. Which is that similar to C that it should be possible to use a C function (at least with minor modifications) – poff Apr 10 '16 at 00:59

1 Answers1

0

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.

  1. Covert the string into numeric parts.

    if (8 == sscanf(buf, "%d-%d-%dT%d:%d:%d%d:%d", &y, &m, ..., &tzh, &tzm)) Success();
    
  2. 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;
    
  3. 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.

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256