如何将纪元时间转换为年份

Use*_*337 7 c c++

我有时间格式.
我只想从中检索年份.

我们应该如何在c或c ++中做到这一点?

实际上我有时间,因为时间秒,我需要根据它来计算年龄.
所以输入将是自纪元以来的秒数,并且输出应该是基于当前日期的年龄.

谢谢,
PP.

Eli*_*ser 6

使用gmtimelocaltime函数将其转换time_t为a struct tm.然后,您可以使用tm_year结构的字段来获取年份.

或者离线使用,您可以使用网络转换器,这样.

编辑:

示例代码:

time_t nowEpoch = time(NULL);
struct tm* nowStruct = gmtime(&nowEpoch);
int year = nowStruct->tm_year + 1900;
Run Code Online (Sandbox Code Playgroud)

  • 用于*离线*的网络转换器? (4认同)

peo*_*oro 5

在 C 中,时间戳(即:从纪元开始的秒数)通常存储在 中time_t,而人类明智的日期存储在结构中tm。您需要一个将time_ts转换为s的函数tm

gmtime或者localtime是两个 C 标准函数来完成你的工作。

struct tm *date = gmtime( your_time );
printf( "Year = %d\n", date->tm_year );
Run Code Online (Sandbox Code Playgroud)

警告这些函数不是线程安全的。您将在 POSIX 系统(linux、mac os x、...)上找到可重入版本:gmtime_rlocaltime_r