Adeed
Adeed

Reputation: 105

Difference of two dates using C++

I am trying to take the difference of two dates by first reading the local time saving the tm structure and going to sleep for 5 seconds and read another local time and saving to another tm structure. I was hoping once I take the differences of the two dates to get a value 5 or greater. However, I am getting 0.

I get the correct result if comment out the following lines:

  oldyear.tm_year = oldyear.tm_year + 1900;
  oldyear.tm_mon = oldyear.tm_mon + 1;


  newyear.tm_year = newyear.tm_year + 1900;
  newyear.tm_mon = newyear.tm_mon + 1;

My code:

void timeTest()
{

  time_t now;
  struct tm newyear, oldyear;
  double seconds;

  time(&now);  /* get current time; same as: now = time(NULL)  */
  oldyear = *localtime(&now);
  oldyear.tm_year = oldyear.tm_year + 1900;
  oldyear.tm_mon = oldyear.tm_mon + 1;

  int epoch1 = mktime(&oldyear);
  sleep(5);
  time(&now);  /* get current time; same as: now = time(NULL)  */

  newyear = *localtime(&now);
 newyear.tm_year = newyear.tm_year + 1900;
  newyear.tm_mon = newyear.tm_mon + 1;

  int epoch2 = mktime(&newyear);

  seconds = difftime(mktime(&newyear),mktime(&oldyear));

  printf ("%.f seconds since new year in the current timezone.\n", seconds);
}

Upvotes: 1

Views: 150

Answers (1)

If I compile this on Linux, a 64-bit system, I get the output

5 seconds since new year in the current timezone.

However, if I compile for 32-bit system,

% gcc -m32 test2.c
% ./a.out
0 seconds since new year in the current timezone.

Note that mktime expects that the year is 1900-based and month 0-based, so the adjustment you do is incorrect and might cause overflow on 32-bit computers. What your code does is calculate the difference of 2 points of time on date 3914-08-28 - on 32-bit systems the time_t usually is 32 bits, and the largest date representable is 03:14:07 UTC on Tuesday, 19 January 2038 aka Y2K38 jf signed time_t is used.

On errors -1 is returned:

If the specified broken-down time cannot be represented as calendar time (seconds since the Epoch), mktime() returns (time_t) -1 and does not alter the members of the broken-down time structure.

Thus if you print out epoch and epoch2 I could bet you get -1 for both these timestamps.

Upvotes: 1

Related Questions