其他分享
首页 > 其他分享> > c – UnixTime到可读日期

c – UnixTime到可读日期

作者:互联网

将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,date,time,unix-timestamp
来源: https://codeday.me/bug/20190929/1829868.html