我试图检查我的应用程序还剩多少天,其中一天来自当前时间,第二天来自数据库的 std::string,但每次我尝试使用减去 2 个日期
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 指出问题我才注意到,不再加类了,谢谢
最佳答案
有两个问题,其中之一是JohnFilleau指出的在评论中。
- 您正在分配给类型而不是变量。就像您正在编码一样:
int = 3;
而不是:
int i = 3;
你需要这样的东西:
tiempo t = end - now;
- 您正在尝试从
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<I>
哪里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);
关于c++ - 使用 std::chrono 两个日期之间还剩多少天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68969702/