【问题标题】:how many days left between 2 dates using std::chrono使用 std::chrono 的两个日期之间还剩多少天
【发布时间】:2021-08-29 03:49:02
【问题描述】:

我正在尝试检查我的应用程序还剩下多少天,一个来自当前时间,第二个来自来自数据库的 std::string,但每次我尝试使用减去两个日期时

std::chrono::duration<int>

我得到“expected unqualified-d before = token”,不确定 chrono 在我的代码下面期待什么

void Silo::RevisarDiasRestantes(){     // Check how many days are left, if the serial is 00 is for life

// obtain the current time with std::chrono and convert to struct tm * so it can be convert to an std::string
std::time_t now_c;
std::chrono::time_point<std::chrono::system_clock> now;
typedef std::chrono::duration<int> tiempo;
struct tm * timeinfo;
char buffer[80]; 

now = std::chrono::system_clock::now();
now_c = std::chrono::system_clock::to_time_t(now);
time (&now_c);
timeinfo = localtime(&now_c);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
std::string str(buffer);

Log("Tiempo usando Chrono " + QString::fromStdString(str));

for (int a{0} ; a<1000 ; )   // just an standard for
{
    a++;
}

//   convert std::string to std::time_t and then convert to a std::chrono
std::string i = str;
std::chrono::time_point<std::chrono::system_clock> end;
struct std::tm tm;
std::istringstream iss;
iss.str(i);
iss >> std::get_time(&tm,"%Y:%m:%d %H:%M:%S");

std::time_t time = mktime(&tm);
end = std::chrono::system_clock::from_time_t(time);
tiempo = end - now;                          <-------------------- heres the problem
Log( "Diferencia de tiempo: " + QString::number(tiempo.count()));

}

编辑:直到今天我才注意到一件事,如果我尝试使用 istringstream 到 std::get_time 程序编译但它在运行时失败,在动态库中要求“缺少 basic_istringstream”,所以我不能使用那;是否有另一种方法可以将字符串提供给 get_time?

Edit2:直到 JhonFilleau 指出问题,我才注意到,不再加班,谢谢

【问题讨论】:

  • tiempo 等价于std::chrono::duration&lt;int&gt;。您正在输入std::chrono::duration&lt;int&gt; = end - now;。你看到问题了吗?这就像int = 2 - 1;

标签: c++ chrono


【解决方案1】:

这里有两个问题,其中一个是由 cmets 中的JohnFilleau 指出的。

  1. 您正在分配给一个类型而不是一个变量。就好像你在编码:

 

int = 3;

代替:

int i = 3;

你需要这样的东西:

tiempo t = end - now; 
  1. 您正在尝试从system_clock::time_point 的精度(通常为微秒到纳秒)隐式转换为秒的精度。而且 chrono 不会让您隐式执行该转换,因为它会丢失精度。

但是你可以用duration_cast强制它:

tiempo t = std::chrono::duration_cast<std::chrono::seconds>(end - now);

终于不用了

typedef std::chrono::duration<int> tiempo;

这只是seconds 的另一个名称,但存储在int 中,而不是不太容易溢出的东西。 auto 在这里可以更方便地使用:

auto t = std::chrono::duration_cast<std::chrono::seconds>(end - now);

t 的类型是std::chrono::duration&lt;I&gt;,其中I 是至少 35 位(通常为 64 位)的有符号整数类型。这种类型有一个方便的类型别名,名为std::chrono::seconds

如果你真的想要这种名为 tiempo 的类型,那么我建议:

using tiempo = std::chrono::seconds;
// ...
auto t = std::chrono::duration_cast<tiempo>(end - now);

或:

tiempo t = std::chrono::duration_cast<tiempo>(end - now);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-29
    • 2011-03-30
    • 2020-02-11
    • 2011-11-20
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多