将 unix 时间戳转换为人类可读的日期

Convert unix timestamp to human readable date

本文关键字:日期 人类 unix 时间戳 转换      更新时间:2023-10-16

有没有一种现代方法可以将 unix 时间戳转换为人类可读的日期? 由于我想绕过 2038 年的问题,我想使用 int64s。 我的目标是将例如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 的日期库来试验此扩展<chrono>功能,方法是添加:

#include "date/date.h"

using namespace date;

到上面的程序。 您可以在此处在线尝试此程序。


下面的评论询问如果值存储在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++等事物出现之前设计的,而2001年仅与科幻小说有关(例如gmtime(。

包装器

#include <chrono>
char* get_time(time_t unix_timestamp)
{
char time_buf[80];
struct tm ts;
ts = *localtime(&unix_timestamp);
strftime(time_buf, sizeof(time_buf), "%a %Y-%m-%d %H:%M:%S %Z", &ts);
return time_buf;
}

Howard Hinnant的日期库使事情变得非常简单:

#include "date.h"
int main()
{
using namespace date;
time_t time = 32879409516;
auto sysTime = std::chrono::system_clock::from_time_t(time);
auto date = year_month_day(floor<days>(sysTime));
std::cout << date << "n";
}

一个很好的直接解决方案,但可以做一些小的更改:

uint32_t days = (uint32_t)floor(subt / 86400);
uint32_t hours = (uint32_t)floor(((subt - days * 86400) / 3600) % 24);
uint32_t minutes = (uint32_t)floor((((subt - days * 86400) - hours * 3600) / 60) % 60);
uint32_t seconds = (uint32_t)floor(((((subt - days * 86400) - hours * 3600) - minutes * 60)) % 60);
printf("Time remaining: %u Days, %u Hours, %u Minutes, %u Secondsn", days, hours, minutes, seconds);