gmtime给了我一些当地时间

gmtime is giving me some times localtime?

本文关键字:当地时间 gmtime      更新时间:2023-10-16

我在多线程环境中打印事件控制台是所有线程共享的静态互斥体。

问题是每一百或一千个事件随机发生一次,我得到的时间是当地时间,而不是UTC。

我只在Linux机器中看到过这个错误(使用g++构建),但在Windows中没有(使用VC++构建)。我不知道从哪里开始,知道吗?

void  Publish(std::string source, std::string topic, std::string msg) NOEXCEPT {
    console.lock();
    std::time_t now = std::chrono::high_resolution_clock::to_time_t(*localTime);
    char buf[50];
    strftime(buf, sizeof (buf), "%Y-%m-%dT%H:%M:%S+00:00", gmtime(&now));
    cout << buf << " " << source << " " << topic << " " << msg << endl;
    cout.flush();
    console.unlock();
}
struct tm * gmtime (const time_t * timer);

将time_t转换为tm作为UTC时间。此调用使用计时器指向的值来用表示相应时间的值填充tm结构,该值表示为UTC时间(即GMT时区的时间)。

这必须正常工作。然而,不确定这一点:

 std::time_t now = std::chrono::high_resolution_clock::to_time_t(*localTime);

在多线程情况下,您的*localtime是否准确地给出了当前时间?它是一个共享变量吗?相反,你可以使用以下方法:

std::time_t now = time(0);