gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:48:46 25 4
gpt4 key购买 nike

这不像我在网上找到的例子那么困难。我正在尝试创建一个 std::chrono::system_time基于某些 UTC 日期。我在单线程中工作的代码如下:

#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;
}

请注意,我在不同的时区打印以确保 setenv 正常工作。是否有线程安全的方法可以从 UTC 日期创建 C++11 时间?

最佳答案

在 C++20 中(是的,我知道你没有 C++20,请坚持使用我)你将能够做到这一点:

#include <chrono>

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

您可以通过使用 Howard Hinnant's free, open-source, header-only library 在 C++11 中使用此语法。 :
#include "date/date.h"

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

不同之处在于新名称在 namespace date 中。而不是 namespace std::chrono ,和 UDL y更名为 _y .

这既高效又线程安全。如果您更愿意自己编写代码, here are the algorithms this library uses .

关于c++ - 如何从 UTC 日期创建 C++11 system_time(线程安全),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60191404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com