Posted by Kieren Searle on the 04/21/09

Compare two dates in C++

When comparing two dates that are of the data type string they will need to be first converted to dates. Once this is done a simple comparison test is possible.

Code:

void compareDates(string date1, string date2) {
  //create a time_t object
  time_t rawtime;
  time(&rawtime);
 
  //create a tm structure and load in date1
  struct tm * timeinfo1;
  timeinfo1 = localtime(&rawtime);
  timeinfo1->tm_year = atoi(date1.substr(6).c_str()) - 1900;
  timeinfo1->tm_mon = atoi(date1.substr(3, 2).c_str()) - 1;
  timeinfo1->tm_mday = atoi(date1.substr(0, 2).c_str());
 
  //create a tm structure and load in date2
  struct tm * timeinfo2;
  timeinfo2 = localtime(&rawtime);
  timeinfo2->tm_year = atoi(date2.substr(6).c_str()) - 1900;
  timeinfo2->tm_mon = atoi(date2.substr(3, 2).c_str()) - 1;
  timeinfo2->tm_mday = atoi(date2.substr(0, 2).c_str());
  
  //compare the dates
  if(timeinfo1 > timeinfo2) cout << "date1 is the latest date";
  else cout << "date2 is the latest date";
}

This function takes two strings, date1 and date2. Both dates are in the format of dd-mm-yyyy. Note that the hyphens can be any character as the sub-strings ignores them.

The function works by creating two tm objects and loading in some demo time data from our time_t object at the beginning of the function. This creates two identical time/date objects. We then overwrite the dates in these objects with our two dates. Once complete we have our two identical date/time objects but now with our two dates overwriting the date parts.

The final lines simply compare the two dates and outputs whichever one is the latest.

Trackback address for this post

This is a captcha-picture. It is used to prevent mass-access by robots.
Please enter the characters from the image above. (case insensitive)

No feedback yet

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)
This is a captcha-picture. It is used to prevent mass-access by robots.
Please enter the characters from the image above. (case insensitive)

My name is Kieren and this is my blog. I use it mostly to document any solutions to problems I come across in computing.

Search

XML Feeds