Search code examples
c++timecomparec++-chrono

Chrono, c++, comparing dates


I have Problem with comparing dates from chrono library. For example, something should happen when the date_to_do_something is matched with the current date.

#include <iostream>
#include <chrono> 
#include <typeinfo>
using namespace std;

int main(){
 end = chrono::system_clock::now();
 string date_to_do_something ="Tue Jul 27 17:13:17 2021";  
 time_t end_time = chrono::system_clock::to_time_t(end);
 //gives some weird types:pc, pl
 cout<<typeid(ctime(&end_time)).name()<<endl;
 cout<<typeid(&end_time).name()<<endl;
 //Now how to compare?
 
}



Solution

  • First of all, pc and pl types are types char* and long*. If you want to print the full type name using typeid pipe your output to c++filt, something like ./prog | c++filt --types. To compare these two dates, you should convert std::string to time_t. For that use tm structure. To convert string to time use strptime() function from time.h header. After that create time_point value using from_time_t() and mktime(). And at the end convert time_point_t type to time_t with to_time_t() function.

    Your code should be something like this:

      auto end = chrono::system_clock::now();
      string date_to_do_something = "Mon Jul 27 17:13:17 2021";
      time_t end_time = chrono::system_clock::to_time_t(end);
      // gives some weird types:pc, pl
      cout << typeid(ctime(&end_time)).name() << endl;
      cout << typeid(&end_time).name() << endl;
      // Now how to compare?
      tm t = tm{};
      strptime(date_to_do_something.c_str(), "%a %b %d %H:%M:%S %Y", &t);
      chrono::system_clock::time_point tp =
          chrono::system_clock::from_time_t(mktime(&t));
      time_t time = chrono::system_clock::to_time_t(tp);
      if (time == end_time) {
        // do something
      } else {
        // do something else
      }