linux获取系统时间和时间戳

linux获取系统时间和时间戳

linux下c/c++编程需要系统时间,一个是获取时间戳和计算时间差,一个获取当前时间用来作为文件名等,方法和例子如下:
可以用man命令查询time,localtime,gettimeofday用法,注意struct tm和struct timeval用法;

man localtime

NAME
asctime, ctime, gmtime, localtime, mktime, asctime_r, ctime_r, gmtime_r, localtime_r - transform date and time
to broken-down time or ASCII

SYNOPSIS
#include

char *asctime(const struct tm *tm);
char *asctime_r(const struct tm *tm, char *buf);

char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);

struct tm *gmtime(const time_t *timep);
struct tm *gmtime_r(const time_t *timep, struct tm *result);

struct tm *localtime(const time_t *timep);
struct tm *localtime_r(const time_t *timep, struct tm *result);

time_t mktime(struct tm *tm);

SEE ALSO
date(1), gettimeofday(2), time(2), utime(2), clock(3), difftime(3), strftime(3), strptime(3), timegm(3),
tzset(3), time(7)

man gettimeofday
NAME
gettimeofday, settimeofday - get / set time

SYNOPSIS
#include

int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);

SEE ALSO
date(1), adjtimex(2), time(2), ctime(3), ftime(3), capabilities(7), time(7)

获取当前时间用来作为文件名
#include
#include

int main()
{
	struct tm *t;
	time_t tt;
	time_t ts;

	struct tm tr = {0};

	time(&tt);
	t = localtime(&tt);
	printf("localtime %4d%02d%02d %02d:%02d:%02d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);

	localtime_r(&tt, &tr);
	printf("localtime_r %4d%02d%02d %02d:%02d:%02d\n", tr.tm_year + 1900, tr.tm_mon + 1, tr.tm_mday, tr.tm_hour, tr.tm_min, tr.tm_sec);

	ts = tt + 1800;
	t = localtime(&ts);
	printf("localtime %4d%02d%02d %02d:%02d:%02d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);

	localtime_r(&ts, &tr);
	printf("localtime_r %4d%02d%02d %02d:%02d:%02d\n", tr.tm_year + 1900, tr.tm_mon + 1, tr.tm_mday, tr.tm_hour, tr.tm_min, tr.tm_sec);

	return 0;
}



$ ./timet1
localtime 20161108 15:03:46
localtime_r 20161108 15:03:46
localtime 20161108 15:33:46
localtime_r 20161108 15:33:46


获取时间戳和计算时间差
#include 
#include 
#include 

int main()
{
	struct timeval tv;
	struct timezone tz;

	struct timeval ts;
	int i = 0;

	gettimeofday(&tv, &tz);
	printf("tv_sec %ld\n", tv.tv_sec);
	printf("tv_usec %ld\n", tv.tv_usec);
	printf("tz_minuteswest %d\n", tz.tz_minuteswest);
	printf("tz_dsttime %d\n",tz.tz_dsttime);

	gettimeofday(&tv, &tz);
	printf("%ld.%ld \n", tv.tv_sec, tv.tv_usec / 1000);

	//timestamp
	gettimeofday(&tv, NULL);
	printf("%ld.%ld \n", tv.tv_sec, tv.tv_usec / 1000);
	usleep(30000);
	gettimeofday(&ts, NULL);
	printf("%ld.%ld \n", ts.tv_sec, ts.tv_usec / 1000);
	printf("timestamp: %ld ms \n", (ts.tv_sec * 1000 + ts.tv_usec / 1000) - (tv.tv_sec * 1000 + tv.tv_usec / 1000));

	return 0;
}



$ ./timet2
tv_sec 1478589648
tv_usec 329048
tz_minuteswest -480
tz_dsttime 0
1478589648.329
1478589648.329
1478589648.359
timestamp: 30 ms

你可能感兴趣的:(linux)