Linux C 获取当前日期时间的封装

使用gettimeofday可以获取到从epoch(1970-1-1 00:00:00)开始的年月日时分秒,但是有时候希望获取到精确到微秒的时间,所以将localtime_r封装进去用于获取微秒,具体代码如下。
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <assert.h>
#include <unistd.h>

/*
********************************************************************************
* 定义模块结构体
********************************************************************************
*/
typedef struct {
    unsigned short year;
    unsigned char  mon;
    unsigned char  day;
} DATE_T;               /* 日期 */

typedef struct {
    unsigned char  hour;
    unsigned char  min;
    unsigned char  sec;
    unsigned int   usec;
} TIME_T;               /* 时间 */

typedef struct {
    DATE_T         date;
    TIME_T         time;
} SYSTIME_T;            /* 日期+时间 */

/*
********************************************************************************
* 定义模块局部变量
********************************************************************************
*/
static SYSTIME_T sys_time;

/**
 * 函数名:get_cur_time
 * 函数描述:获取当前的系统时间(精确到微秒)
 * 参数:无
 * */
static void get_cur_time(SYSTIME_T *sys_t)
{
	assert(NULL != sys_t);
	struct timeval  tv;
	struct tm tm;

    gettimeofday(&tv, NULL);
    localtime_r(&tv.tv_sec, &tm);

	sys_t->date.year = tm.tm_year + 1900;
	sys_t->date.mon = tm.tm_mon + 1;
	sys_t->date.day = tm.tm_mday;
	sys_t->time.hour = tm.tm_hour;
	sys_t->time.min = tm.tm_min;
	sys_t->time.sec = tm.tm_sec;
	sys_t->time.usec = tv.tv_usec;
}

int main()
{
	SYSTIME_T sys_time;
	memset(&sys_time, 0, sizeof(SYSTIME_T));
	get_cur_time(&sys_time);

	printf("year = %d, month = %d, day = %d, hour = %d, minute = %d, second = %d, usec = %d\n", 
		sys_time.date.year, sys_time.date.mon, sys_time.date.day, sys_time.time.hour, 
		sys_time.time.min, sys_time.time.sec, sys_time.time.usec);
		
	return 0;
}

发布了62 篇原创文章 · 获赞 106 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/lang523493505/article/details/90039866