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(¤tTime));
}
int main()
{
std::cout << GetSystemTime();
}
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(¤tTime), "%F %T");
return os.str();
}
Note about std::gmtime
: This function may not be thread-safe.