在C posix中如何拥有时间戳?



大家好,C怎么可能有时间戳? 在 bash 中很容易日期 +"%s",但在 C 中,我找不到任何关于这一点的东西,只有当您有时间戳并希望在正常日期中转换时,我才发现这一点,但 viceversa ?还是像 bash 中那样存在一个简单的命令?

time_t     now;
struct tm  ts;
char       buf[80];
// Get current time
time(&now);
// Format time, "ddd yyyy-mm-dd hh:mm:ss zzz"
ts = *localtime(&now);
strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", &ts);
printf("%sn", buf);```

您正在寻找的函数是strptimestrftime

strptime会将字符串日期解析为tm结构,strftime会将tm结构的格式设置为字符串。

tm结构转换为 POSIX 时间戳和从 POSIX 时间戳转换是相当简单的。

从引用的手册页中窃取:

#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int
main(void)
{
struct tm tm;
char buf[255];
memset(&tm, 0, sizeof(tm));
strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);
strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
puts(buf);
exit(EXIT_SUCCESS);
} 

tm结构之间的转换最好使用gmtime/timegm对来完成。

最新更新