【问题标题】:Chrono, c++, comparing datesChrono,C++,比较日期
【发布时间】:2021-07-19 17:23:03
【问题描述】:

我在比较 chrono 库中的日期时遇到问题。 例如,当 date_to_do_something 与当前日期匹配时,应该会发生一些事情。

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


【问题讨论】:

标签: c++ time compare chrono


【解决方案1】:

首先,pcpl 类型是 char*long* 类型。如果您想使用typeid 打印完整的类型名称,请将您的输出传送到c++filt,类似于./prog | c++filt --types。 要比较这两个日期,您应该将std::string 转换为time_t。为此使用tm structure。要将字符串转换为时间,请使用 time.h 标头中的 strptime() 函数。之后使用from_time_t()mktime() 创建time_point 值。最后使用to_time_t()函数将time_point_t类型转换为time_t

你的代码应该是这样的:

  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
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多