如何使用 chrono 获取 UTC 格式的系统时间

How to get system time in UTC format using chrono

我正在尝试使用 chrono 查找 UTC 格式的系统时间。我想下面的程序只给我当地时间,请有人帮我吗?

#include <iostream>
#include <chrono>
#include <ctime>  

auto GetSystemTime() -> uint8_t * {
auto now = std::chrono::system_clock::now();
std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
return reinterpret_cast<uint8_t *>(std::ctime(&currentTime));
}

int main()
{

   std::cout << GetSystemTime();
    
}

以下是如何将此 free, open-source, header-only preview of C++20 <chrono> 与 c++11/14/17 一起使用:

#include "date/date.h"
#include <chrono>
#include <iostream>

auto
GetSystemTime()
{
    return date::format("%F %T %Z", std::chrono::system_clock::now());
}

int
main()
{
    std::cout << GetSystemTime() << '\n';
}

使用:

clang++ -std=c++17 test.cpp -I../date/include

这只是为我输出:

2021-03-10 21:49:51.861588 UTC

您可以根据需要使用 these formatting flags.

格式化它

如果您坚持使用 C++11 - C++17,您可以使用 std::gmtime which "converts given time since epoch as std::time_t value into calendar time, expressed in Coordinated Universal Time (UTC)" and then std::put_time 将其格式化为您想要的格式。

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

std::string GetSystemTime() {
    auto now = std::chrono::system_clock::now();
    std::time_t currentTime = std::chrono::system_clock::to_time_t(now);

    std::ostringstream os;
    os << std::put_time(gmtime(&currentTime), "%F %T");

    return os.str();
}

Demo

关于 std::gmtime 的注意事项:此函数可能不是线程安全的。