3

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?
 
}


  • 1
    Does this answer your question? [How to parse a date string into a c++11 std::chrono time\_point or similar?](https://stackoverflow.com/questions/21021388/how-to-parse-a-date-string-into-a-c11-stdchrono-time-point-or-similar) –  Jul 19 '21 at 17:25
  • What should happen if Jul 27, 2021 isn't a Monday? – Howard Hinnant Jul 19 '21 at 17:34
  • It doesnt matter I just gave an example. – Lordoftherings Jul 19 '21 at 17:36

1 Answers1

1

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
  }
Dzemo997
  • 328
  • 2
  • 5