I was wondering if there is any relatively easy and short date comparison functions in C++.
My dates are of type char*
, and have the following format: DD
If this is really a fixed format, you can do it with simple C string comparison
int date_cmp(const char *d1, const char *d2)
{
int rc;
// compare years
rc = strncmp(d1 + 6, d2 + 6, 4);
if (rc != 0)
return rc;
// compare months
rc = strncmp(d1 + 3, d2 + 3, 2);
if (rc != 0)
return rc;
// compare days
return strncmp(d1, d2, 2);
}
This works like strncmp. It returns a value less than 0, if d1
is earlier than d2
, 0 if both are the same date, and a value greater than 0, if d1
is later than d2
.
Another approach would be to convert it with strptime and mktime to time_t
and compare these with difftime
struct tm tm;
time_t t1, t2;
strptime(d1, "%d\\%m\\%Y", &tm);
t1 = mktime(&tm);
// do the same with d2
double diff = difftime(t1, t2);