将 unix 时间戳转换为人类可读的日期
Convert unix timestamp to human readable date
有没有一种现代方法可以将 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);
相关文章:
- 查询SQLite数据库中的日期
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- Log4cpp:以UTC/GMT时区打印日期
- 使用C++的日期库读取时间
- 日期格式为C++
- 如何在 C++20 计时中为日期添加天数?
- 如何在QTableView中排序和更改日期格式
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- Gtkmm 会不断检查 Gtk::日历上的所选日期是否发生变化
- fmt 与 Howard Hinnant 的日期:为什么从 fmt::to_string "{}"?FMT 和日期的最佳实践?
- 使程序检查当前日期是否=预期日期
- 将自定义 QMap 模板实例化以人类可读的形式保存在 QSettings 中
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- JNI 日期值转换问题,在C++中获取不同的长整型值
- 确定夏令时是否适用于特定日期
- C++日期库因时区而失败
- 将 unix 时间戳转换为人类可读的日期
- 将人类可读日期转换为毫秒,然后再转换回来,而不会丢失信息
- 将UTC毫秒转换为人类可读日期时间
- 提高简单的人类可读的日期时间