Search code examples
c++c++14c++17

How to get system time in UTC format using chrono


I am trying to find the system time in UTC format using the chrono. I think the following program only gives me local time , please can some one help me out ?

#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();
    
}

Solution

  • If you're stuck with C++11 - C++17, you could use 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 to format it the way you want.

    #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

    Note about std::gmtime: This function may not be thread-safe.