C++ 在C+中验证特定持续时间的时间戳+;
我想通过查看数据的时间戳来查看我的数据是否有120秒的历史,因此我有以下代码:C++ 在C+中验证特定持续时间的时间戳+;,c++,c++11,timestamp,C++,C++11,Timestamp,我想通过查看数据的时间戳来查看我的数据是否有120秒的历史,因此我有以下代码: uint64_t now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count(); bool is_old = (120 * 1000 < (now - data_holder->getTimestamp())); uint64\u t now=duration\u cast(稳定的时钟::n
uint64_t now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
bool is_old = (120 * 1000 < (now - data_holder->getTimestamp()));
uint64\u t now=duration\u cast(稳定的时钟::now().time\u自\u epoch()).count();
bool是旧的=(120*1000<(现在-data\u holder->getTimestamp());
在上面的代码中,
data\u holder->getTimestamp()
是uint64\u t
,它以毫秒为单位返回时间戳。我上面的代码看起来正确吗?我可能会这样做:
auto now = system_clock::now().time_since_epoch();
// Use the correct time duration below. Milliseconds could be wrong, see 1)
auto diff = now - std::chrono::milliseconds(data_holder->getTimestamp());
bool is_old = diff > std::chrono::seconds{120};
// bool is_old = diff > 120s; // From C++14 onwards.
1) 如前所述,毫秒
可能是用于getTimestamp()
的错误单位。所有可能的类型都是
std::chrono::hours
std::chrono::minutes
std::chrono::seconds
std::chrono::milliseconds
std::chrono::microseconds
std::chrono::nanoseconds
您可能必须尝试使用哪一个,因为这取决于data\u holder->getTimestamp()
注:大的 确保使用
system\u clock
来测量时间,因为epoch最有可能起作用。但是该标准并不要求时钟的历元是UNIX历元。您已经在稳定时钟
中遇到过这种情况
你必须计算时钟的历元和你自己的历元之间的差值(我现在不知道有什么方法可以计算任何时钟的历元)。对于系统时钟
,如果您不相信它会使用unix epoch,则可以使用以下命令:
system_clock::duration time_since_unix_epoch()
{
std::tm epoch;
epoch.tm_mday = 1;
epoch.tm_mon = 0;
epoch.tm_year = 70;
std::time_t epocht = mktime(&epoch);
return system_clock::now() - system_clock::from_time_t(epocht);
}
而不是系统时钟::now()
。我更喜欢这种方法
不幸的是,您不能仅仅用另一个来自
std::chrono
的时钟替换system\u clock
,因为只有std::system\u clock
提供了from\u time\t(time\t)
功能,它将实际日期转换为时钟使用的内部时间点 你试过一些简单的测试吗?看起来不错,但这不是一个真正的问题。是的,我尝试过,但不知何故,当我得到now
变量的值时,我弄糊涂了计数是如何工作的。对于像这样的简单示例现在:7853385数据保持器时间戳:1437518224112
。这是如何工作的?您是如何分配data\u holder->getTimestamp()
?@JonathanMeedata\u holder->getTimestamp()
总是以毫秒为单位返回时间戳。谢谢您的建议data\u holder->getTimestamp()
将以毫秒为单位返回时间戳。你能帮我理解一下吗?我的now变量值是10011360
,数据持有者时间戳值是143752038241
,那么为什么now-data\u holder->getTimestamp()
的18446742636199180735
会出现差异呢。它应该是负的,对吗?上面的结果与我的代码是一样的。有什么想法吗?嗯,我也很困惑伯爵在干什么。但当我现在打印出数据持有者的时间戳时,我得到了上面的细节,如果我减去它,它应该是负数,那么为什么它是正数呢?谢谢你的帮助。稳定时钟
与系统时钟
之间有什么区别?我无法理解这一点。而且,如果我需要使用我在问题中的解决方案,我可以用系统时钟
替换稳定时钟
,对吗?@user1950349,区别是相当技术性的<代码>稳定的时钟
在我的理解中保证永远不会被重置,因此是单调的,而系统时钟
被设计用来表示计算机的日历日期。不,你不能只是替换它们,见答案的最后一段。