问题描述
如何在C ++中获得uint
Unix时间戳?我在Google上搜索了一下,似乎大多数方法都在寻找更复杂的方法来表示时间.我不能仅仅以uint
的身份获得它吗?
How do I get a uint
unix timestamp in C++? I've googled a bit and it seems that most methods are looking for more convoluted ways to represent time. Can't I just get it as a uint
?
推荐答案
C ++ 20引入了保证,即 time_since_epoch
将相对于UNIX时代,并给出此示例(以秒为单位,而不是以小时为单位,提取到相关代码中):
C++20 introduced a guarantee that time_since_epoch
will be relative to the UNIX epoch, and gives this example (distilled to relevant code, and in units of seconds rather than hours):
#include <iostream>
#include <chrono>
int main()
{
const auto p1 = std::chrono::system_clock::now();
std::cout << "seconds since epoch: "
<< std::chrono::duration_cast<std::chrono::seconds>(
p1.time_since_epoch()).count() << '\n';
}
使用C ++ 17或更早版本, time()
是最简单的功能-自Epoch以来的秒数,对于Linux和UNIX,至少是UNIX纪元. Linux联机帮助页此处.
Using C++17 or earlier, time()
is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.
上面链接的cppreference页面提供了以下示例:
The cppreference page linked above gives this example:
#include <ctime>
#include <iostream>
int main()
{
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result))
<< result << " seconds since the Epoch\n";
}
这篇关于使用C ++获取Unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!