是否有现代方法将 unix 时间戳转换为人类可读的日期? 由于我想绕过 2038 年的问题,所以我想使用 int64s。 我的目标是转换 e。 G。 1205812558转
年 = 2008,月 = 3,日 = 18, 小时 = 17,分钟 = 18,秒 = 36
我只有现在
auto year = totalSeconds / secondsPerYear + 1970;
// month and day missing
auto hours = totalSeconds / 3600 % 24;
auto minutes = totalSeconds / 60 % 60;
auto seconds = totalSeconds % 60;
最佳答案
在 C++20 中(根据目前的 C++20 规范草案),您将能够说:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
cout << sys_seconds{1205812558s} << '\n';
cout << sys_seconds{32879409516s} << '\n';
}
它会输出:
2008-03-18 03:55:58
3011-11-28 17:18:36
这些是 UTC 的日期时间。
您可以使用 Howard Hinnant's date library试验这个扩展 <chrono>
今天的功能通过添加:
#include "date/date.h"
和
using namespace date;
到上面的程序。你可以experiment online with this program here .
下面的评论询问如果值存储在 uint64_t
中会是什么样子? .答案是需要把整型转成seconds
,然后是 seconds
至 sys_seconds
:
uint64_t i = 1205812558;
cout << sys_seconds{seconds(i)} << '\n';
此现代功能确实存在限制,但它们的生命周期接近 +/-32K 年(远远超出当前民用日历的准确性限制)。
为了完全透明,确实存在仅使用 C++98/11/14/17 来执行此操作的方法,但它们比这更复杂,并且容易受到多线程错误的影响。这是由于使用了过时的 C API,该 API 是在多线程和 C++ 出现之前设计的,并且当 year 2001 was only associated with science fiction 出现时。 (例如 gmtime
)。
关于c++ - 将 unix 时间戳转换为人类可读的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51993887/