使用 C++ 获取 Unix 时间戳 [英] Get Unix timestamp with C++

查看:98
本文介绍了使用 C++ 获取 Unix 时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C++ 中获得 uint unix 时间戳?我用谷歌搜索了一下,似乎大多数方法都在寻找更复杂的方式来表示时间.我不能把它作为 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 epoch,而 cppreference.com 给出了一个例子,我已经将相关代码提炼出来,并更改为秒而不是小时的单位:

C++20 introduced a guarantee that time_since_epoch is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to 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() << '
';
}


使用 C++17 或更早版本,time() 是最简单的函数——自Epoch以来的秒数,对于Linux和UNIX至少是UNIX时代.Linux 手册页在这里.

上面链接的 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
";
}

这篇关于使用 C++ 获取 Unix 时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆