gpt4 book ai didi

c++ - UnixTime 到可读日期

转载 作者:可可西里 更新时间:2023-11-01 15:49:28 29 4
gpt4 key购买 nike

将 UnixTime 转换为日期的最佳方法是什么?

是否有针对它的函数或算法?

最佳答案

Unix 时间是自纪元 (1970-01-01) 以来的秒数。根据您的意思,您可以使用 localtime 将其转换为 struct tm或使用 strftime 将其转换为字符串.

time_t t = time(NULL);
struct tm *tm = localtime(&t);
char date[20];
strftime(date, sizeof(date), "%Y-%m-%d", tm);

作为本地时间状态的手册

The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.

这就是一些人所说的数据竞争。当两个或多个线程同时调用 localtime 时,就会发生这种情况。

为了避免这种情况,一些人建议使用 localtime_s,这是 Microsoft 独有的功能。在 POSIX 系统上,您应该使用 localtime_r 代替

The localtime_r() function does the same, but stores the data in a user-supplied struct.

用法看起来像

time_t t = time(NULL);
struct tm res;
localtime_r(&t, &res);

关于c++ - UnixTime 到可读日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13536886/

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