UnixTime可读取日期 [英] UnixTime to readable date
问题描述
可能重复:
C ++:获取当前时间和日期
什么是将UnixTime转换为日期的最佳方法?
What is the best way to convert UnixTime to a date?
是否有一个函数或算法?
Is there a function for it or an algorithm?
推荐答案
Unix时间是从epoch(1970-01-01)开始的秒。根据您的意思,您可以将其转换为 struct tm
与 localtime 或将其转换为带有 strftime 。
Unix time is seconds since epoch (1970-01-01). Depending on what you mean, you can convert it to a struct tm
with localtime or convert it to a string with strftime.
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char date[20];
strftime(date, sizeof(date), "%Y-%m-%d", tm);
作为本地时间状态的手册
As the manual to localtime states
返回值指向静态分配的
结构,可能会被以后调用覆盖到任何
日期和时间函数
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
时,会发生这种情况。
This is what some refer to as data races. This happens when two or more threads call localtime
simultaneously.
为了防止这种情况,有些建议使用 localtime_s
,这是一个仅Microsoft功能。在POSIX系统上,您应该使用 localtime_r
To protect from this, some suggest using localtime_s
, which is a Microsoft only function. On POSIX systems, you should use localtime_r
instead
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(&t, &res);
这篇关于UnixTime可读取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!