c++ - 使用 VC141 将 high_resolution_clock::time_point 转换为 time_t

标签 c++ std c++-chrono

我刚刚在 Visual Studio 2013 中使用

#include <chrono>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <sstream>

std::string Time_Point_String(const std::chrono::high_resolution_clock::time_point & timePoint)
{
    time_t timeNow = std::chrono::system_clock::to_time_t(timePoint);

    tm time = *localtime(&timeNow);

    std::stringstream timeString;
timeString << std::setfill('0') << 1900 + time.tm_year << "-" << std::setw(2) << time.tm_mon + 1 << "-" << std::setw(2) << time.tm_mday << " " << std::setw(2) << time.tm_hour << ":" << std::setw(2) << time.tm_min << ":" << std::setw(2) << time.tm_sec;

    return timeString.str();
}

int main()
{
    const std::chrono::high_resolution_clock::time_point & timePoint = std::chrono::high_resolution_clock::now();

    std::cout << Time_Point_String(timePoint);
    return 0;
}

但是在 Visual Studio 2017 中我得到一个编译器错误:

Error C2664 '__time64_t std::chrono::system_clock::to_time_t(const std::chrono::system_clock::time_point &) noexcept': cannot convert argument 1 from 'const std::chrono::steady_clock::time_point' to 'const std::chrono::system_clock::time_point &'

因此不再可能将 high_resolution_clock::time_point 转换为不同的 time_point,例如 system_clock::time_point,并且有无法将 high_resolution_clock::time_point 直接转换为 time_t

我该如何处理这种情况? 有可能吗(一些 SO 帖子说它们只是完全不同的时钟,转换没有意义)? 据我所知,该函数完成了我在 Visual Studio 2013 应用程序中的预期,它为 high_resolution time_point 提供了正确的本地时间。

最佳答案

这是因为 std::chrono::high_resolution_clockstd::chrono::system_clockstd::chrono::steady_clock 的类型别名:

Class std::chrono::high_resolution_clock represents the clock with the smallest tick period provided by the implementation. It may be an alias of std::chrono::system_clock or std::chrono::steady_clock, or a third, independent clock.

这意味着 std::chrono::high_resolution_clock::time_point 可以是 std::chrono::system_clock::time_point 的类型别名,也可以是另一种类型。根据您的问题,可以猜测它对 MSVC2013 有效,使您的代码有效,但不适用于 MSVC2017,使您的代码无效。

作为结论,以下代码可能有效,也可能无效,以未指定的方式(这取决于编译器及其目标体系结构):

std::chrono::high_resolution_clock::time_point timePoint = /* something */;
std::chrono::system_clock::to_time_t(timePoint);

关于c++ - 使用 VC141 将 high_resolution_clock::time_point 转换为 time_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52292391/

相关文章:

c++ - 如何在不使用数组的情况下将 chrono::time_point 转换为字符串?

c++ - const 是否适用于传递给函数的所有参数?

C++数学函数问题(Linux下)

c++ - std::sort 如何处理对列表?

c++ - 如何将 priority_queue 与类实例的非静态比较方法一起使用?

c++ - 在模板中有没有办法为每个计时实例只编写一个特化? (纳秒、毫秒、秒等)

c++ - 与 stringstream 的链接错误

c++ - std::shuffle 的顺序可以依赖于 RNG 之外的任何东西吗?

c# - 如何配置 IronPython.StdLib 2.7.3

c++ - 当 `sleep_until()` 指定过去的时间点时,行为是否明确?