【问题标题】:What is the correct way to get beginning of the day in UTC / GMT?在 UTC / GMT 中开始一天的正确方法是什么?
【发布时间】:2022-11-30 00:13:46
【问题描述】:
::tm tm{0, 0, 0, 29, 10, 2022 - 1900, 0, 0};  // 10 for November
auto time_t = ::mktime(&tm);
cout << "milliseconds = " << time_t * 1000 << endl;

以上代码输出1669660200000,相当于2022年11月29日00:00:00.但它在当地时区。如何获取上述日期的 UTC 时间?
具有线程安全性的现代方式将受到赞赏。

【问题讨论】:

  • 现代方式是 std::chrono: en.cppreference.com/w/cpp/chrono 处理时间/日期计算和时区等。
  • timegm/_mkgmtimemktime 的 UTC 等价物,但未标准化

标签: c++17 c++ datetime time c++17 utc


【解决方案1】:

在你的解决方案中有一个挑剔的弱点(除了线程安全问题):tmare not guaranteed to be in the order的成员你假设。

tm 结构应至少包含以下成员,顺序不限。

使用 C++17,你可以使用这个C++20 chrono preview library。它是免费的、开源的并且只有标题。你的程序看起来像:

#include "date/date.h"
#include <chrono>
#include <iostream>

int
main()
{
    using namespace std;
    using namespace chrono;
    using namespace date;

    sys_time<milliseconds> tp = sys_days{2022_y/11/29};
    cout << "milliseconds = " << tp.time_since_epoch().count() << '
';
}

输出将是:

milliseconds = 1669680000000

使用这个库的一个好处是它可以很容易地移植到 C++20。 C++20 版本如下所示:

#include <chrono>
#include <iostream>

int
main()
{
    using namespace std;
    using namespace chrono;

    sys_time<milliseconds> tp = sys_days{2022y/11/29};
    cout << "milliseconds = " << tp.time_since_epoch() << '
';
}

并输出:

milliseconds = 1669680000000ms

Demo:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 2013-01-19
    相关资源
    最近更新 更多