Wednesday, July 22, 2009

Date comparisons in C++

Just been scratching my head over a code snippet that looks like this:

time_t now=...;
time_t last_tick=...;

struct tm *timeinfo=localtime(&now);
...
struct tm *tick_timeinfo=localtime(&last_tick);
...
if(tick_timeinfo->tm_mday==timeinfo->tm_mday &&
  tick_timeinfo->tm_mon==timeinfo->tm_mon &&
  tick_timeinfo->tm_year==timeinfo->tm_year)return OK;
else return BAD;


I'd realized this was code was always returning OK, even when last_tick was yesterday, a month ago, or even from last year.
Can you see the bug? The above is all you need to know. Answers in a comment. No stamp required.

(To be fair to my bruised ego, the problem can really only be one thing in the way I've presented it above.)

Kudos to the first reply. And I'd be interested to hear how people do date comparisons in C++ more safely.

1 comment:

Unknown said...

No-one took up the challenge? Too easy? Too hard?

In case anyone is still scratching their head, the problem is that localtime() returns a global static buffer. So the second call to localtime destroyed the information from the first call.

BTW, that also means localtime is not threadsafe. See discussion here for more:
http://www.codeguru.com/forum/showthread.php?t=331619

localtime_r() is thread-safe, but may be linux only:
http://www.opengroup.org/onlinepubs/000095399/functions/localtime.html