mercredi 12 février 2020

How to Create C++11 system_time from UTC Date (Thread-Safe)

This can't be as difficult as the examples I found online. I am attempting to create a std::chrono::system_time based on some UTC date. The code that I have working in a single thread is the following:

#include <chrono>
#include <iostream>

using namespace std;
using namespace chrono;

int main() {
    // Construct a time to be Jan 1, 2020 00:00:00 UTC
    static tm someTime{
        0, // seconds after the minute - [0, 60] including leap second
        0, // minutes after the hour   - [0, 59]
        0, // hours since midnight     - [0, 23]
        1, // day of the month         - [1, 31]
        0, // months since January     - [0, 11]
      120  // years since 1900
    };
    setenv("TZ", "UTC", 1);
    tzset();
    auto const time = system_clock::from_time_t(mktime(&someTime));
    setenv("TZ", "America/Denver", 1);
    tzset();
    auto const t = system_clock::to_time_t(time);
    cout << ctime(&t) << endl;
    return 0;
}

Note that I am printing in a different timezone to ensure the setenv is working. Is there a thread-safe way to create a C++11 time from a UTC date?

Aucun commentaire:

Enregistrer un commentaire