1

How to convert C++ chrono time in UTC to string in UTC?

Because in my tests when convert chrono time to string it is using different timezone.

Example:

#include <iostream>
#include <string>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <cstdint>
#include <ctime>

std::string getStringFromDateTime(const std::chrono::system_clock::time_point & value) {
    std::time_t time_now_t = std::chrono::system_clock::to_time_t(value);
    std::tm now_tm = *std::localtime(&time_now_t);
    char buf[512];
    std::strftime(buf, 512, "%Y-%m-%d %H:%M:%S %z", &now_tm);
    return buf;
}

std::string getStringFromDateTimeWithGmtime(const std::chrono::system_clock::time_point & value) {
    std::time_t time_now_t = std::chrono::system_clock::to_time_t(value);
    std::tm now_tm = *std::gmtime(&time_now_t);
    char buf[512];
    std::strftime(buf, 512, "%Y-%m-%d %H:%M:%S %z", &now_tm);
    return buf;
}

int main()
{
    std::tm tm = {};
    std::stringstream ss("2018-12-07 20:00:00"); // example of UTC time at 20hs
    ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
    auto dt = std::chrono::system_clock::from_time_t(std::mktime(&tm));

    std::cout << (dt.time_since_epoch().count() / 1000000) << " - EPOCH" << std::endl;

    // 1544212800 - 20:00 - correct (in utc)
    // 1544180400 - 11:00 - wrong (returned by count)

    std::cout << getStringFromDateTime(dt) << " - NORMAL" << std::endl;
    std::cout << getStringFromDateTimeWithGmtime(dt) << " - GMTIME" << std::endl;

    return EXIT_SUCCESS;
}

And i have a wandbox too:

https://wandbox.org/permlink/Bm9c9FCtfP0hCAUn

The result is:

1544180400 - EPOCH
2018-12-07 20:00:00 +0900 - NORMAL
2018-12-07 11:00:00 +0000 - GMTIME

I want the the string store the date/time in UTC too, in the same date/time that i create ("2018-12-07 20:00:00").

Can anyone help me?

Paulo Coutinho
  • 705
  • 1
  • 7
  • 15

0 Answers0