C++ 中的当前 UTC 时间点

Current UTC time point in C++

我想通过网络连接发送一个时间点来检测 ping 时间和进行其他计算。时间必须具有毫秒精度,但使用:

auto currently = std::chrono::time_point_cast<std::chrono::milliseconds>(
    std::chrono::system_clock::now()
);

... returns(当然)系统时间当然不是 UTC。有什么方法可以在不将 time_point 转换为 time_t 然后再转换回来的情况下计算 UTC 值吗?我阅读了一些关于 std::chrono::utc_clock 的内容,但即使使用 C++20,我也无法在 <chrono> header.

中找到定义

编辑

这将是一个可行的解决方案,但它是一个糟糕的解决方案,因为它非常低效......必须有更好的方法:

auto currently = std::chrono::time_point_cast<std::chrono::milliseconds>(
    std::chrono::system_clock::now()
);
time_t time = std::chrono::system_clock::to_time_t(currently);
struct tm *tm = gmtime(&time);
// Create a new time_point from struct tm that is in UTC now

std::chrono::utc_clock 存在于 C++20 标准中,但 clang 和 GCC 都尚未在其标准库中实现它。这对于最新的语言标准来说是很常见的。并非所有编译器都实现了所有功能。

然而,自 C++20 起,std::chrono::system_clock has a specified epoch, namely 1970-01-01 00:00.000 UTC, which is the same as the implied epoch of std::time_t:

system_clock measures Unix Time (i.e., time since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds).

请注意 std::time_t 没有任何指定的纪元,它通常是 1970-01-01 00:00.000 UTC:

Although not defined, this is almost always an integral value holding the number of seconds (not counting leap seconds) since 00:00, Jan 1 1970 UTC, corresponding to POSIX time

所以你需要做的是:

std::chrono::time_point currently = std::chrono::time_point_cast<std::chrono::milliseconds>(
    std::chrono::system_clock::now()
);
std::chrono::duration millis_since_utc_epoch = currently.time_since_epoch();

// use millis_since_utc_epoch.count() to get the milliseconds as an integer