我们知道,通过下面gettimeofday函数的方法获得的是系统的时间戳
struct timeval tv;
gettimeofday(&tv,NULL);
int64_t time = tv.tv_sec*1000 + tv.tv_usec/1000;
那么如何获取到年月日,时分秒,并且精确到毫秒呢?
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
void main()
{
struct timeval tv;
struct timezone tz;
struct tm *t;
gettimeofday(&tv, &tz);
t = localtime(&tv.tv_sec);
printf("%d-%d-%d %d:%d:%d.%ld\n", 1900+t->tm_year, 1+t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, tv.tv_usec);
}
输出结果:
2022-1-19 3:51:8.835209
struct tm的定义:
struct tm
{
int tm_sec; /*秒,正常范围0-59, 但允许至61*/
int tm_min; /*分钟,0-59*/
int tm_hour; /*小时, 0-23*/
int tm_mday; /*日,即一个月中的第几天,1-31*/
int tm_mon; /*月, 从一月算起,0-11*/ 1+p->tm_mon;
int tm_year; /*年, 从1900至今已经多少年*/ 1900+ p->tm_year;
int tm_wday; /*星期,一周中的第几天, 从星期日算起,0-6*/
int tm_yday; /*从今年1月1日到目前的天数,范围0-365*/
int tm_isdst; /*日光节约时间的旗标*/
};
这个结构体是系统定义好的,不需要自己定义