How to get system time in UTC format using chrono

Viewed 867

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

Here is how you can use this free, open-source, header-only preview of C++20 <chrono> with 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';
}

Using:

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

this just output for me:

2021-03-10 21:49:51.861588 UTC

You can format this however you want using these formatting flags.

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.

Related