unix输出时间的几种方式之time函数
作者:互联网
time_t time (time_t* timer);
输出自Unix纪元即1970年1月1日0点0分0秒(国际标准时间)以来的秒数。
示例time.cpp
#include <time.h>
#include <stdio.h>
int main(int argc, char** argv)
{
time_t ticks;
char buff[1024];
ticks = time(NULL); //or time(&ticks);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
printf("%.10ld\r\n", ticks);
printf("%.24s\r\n", buff);
return 0;
}
编译
gcc time.cpp -o time
结果
官方示例中还有一些新玩法:https://www.cplusplus.com/reference/ctime/time/?kw=time
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, difftime, time, mktime */
int main ()
{
time_t timer;
struct tm y2k = {0};
double seconds;
y2k.tm_hour = 0; y2k.tm_min = 0; y2k.tm_sec = 0;
y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1;
time(&timer); /* get current time; same as: timer = time(NULL) */
seconds = difftime(timer,mktime(&y2k));
printf ("%.f seconds since January 1, 2000 in the current timezone", seconds);
return 0;
}
结果
414086872 seconds since January 1, 2000 in the current timezone
标签:y2k,seconds,ticks,timer,几种,unix,tm,time 来源: https://blog.csdn.net/weixin_43129599/article/details/121576154