简体   繁体   English

如何从 UTC 日期创建 C++11 system_time(线程安全)

[英]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.我正在尝试根据某个 UTC 日期创建一个std::chrono::system_time 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.请注意,我在不同的时区打印以确保 setenv 正常工作。 Is there a thread-safe way to create a C++11 time from a UTC date?是否有线程安全的方法可以从 UTC 日期创建 C++11 时间?

In C++20 (yes I know you don't have C++20, just stick with me) you'll be able to do this:在 C++20 中(是的,我知道你没有 C++20,请坚持使用我)你将能够做到这一点:

#include <chrono>

using namespace std::chrono;
system_clock::time_point someTime = sys_days{2020y/1/1};

You can use this syntax in C++11 by using Howard Hinnant's free, open-source, header-only library :您可以通过使用Howard Hinnant 的免费、开源、仅头文件库在 C++11 中使用此语法:

#include "date/date.h"

using namespace date;
using namespace std::chrono;
system_clock::time_point someTime = sys_days{2020_y/1/1};

The difference is that the new names are in namespace date instead of namespace std::chrono , and the UDL y is renamed to _y .不同之处在于新名称位于namespace date而不是namespace std::chrono ,并且 UDL y重命名为_y

This is both efficient and thread-safe.这既高效又线程安全。 If you would rather code it yourself, here are the algorithms this library uses .如果您更愿意自己编写代码,这里是该库使用的算法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM