C ++中的当前UTC时间点 编辑

问题描述

我想通过网络连接发送时间点以检测ping时间并进行其他计算。时间必须具有毫秒级的精度,但是要使用:

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

...(当然)返回的系统时间当然不是UTC。有什么方法可以在不将time_point转换为time_t然后又返回的情况下计算UTC值吗?我读到一些关于std::chrono::utc_clock内容,但是即使使用C ++ 20,我也无法在<chrono>标头中找到该定义。

编辑@H_502_17@

这将是一个可行的解决方案,但这是一个糟糕的解决方案,因为它效率很低……必须有更好的解决方法

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具有指定的纪元,即1970-01-01 00:00.000 UTC,与std::time_t的隐含纪元相同:

system_clock测量Unix时间(即,自1970年1月1日星期四00:00:00协调世界时(UTC)起的时间,不计算leap秒)。

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

尽管未定义,但它几乎始终是一个整数值,用于保存自1970年1月1日世界标准时间00:00开始的秒数(不计算leap秒),对应于POSIX时间

所以您需要做的是:

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