获取毫秒时间戳
#ifndef HELLOWORDC_TIME_UTILS_H
#define HELLOWORDC_TIME_UTILS_H
#if defined(__WIN32)
#include <sys/timeb.h>
#elif defined(__UNIX__) || defined(__APPLE__)
#include <sys/time.h>
#else
#include <time.h>
#endif
typedef long long long_time_t;
//返回毫秒时间戳
long_time_t TimeInMillisecond(void){
#if defined(__WIN32)
struct timeb time_buffer;
ftime(&time_buffer);
return time_buffer.time * 1000LL +time_buffer.millitm;
#elif defined(__unix__) || defined(__APPLE__)
struct timeval time_value;
gettimeofday(&time_value,NULL);
return time_value.tv_sec * 1000LL + time_value.tv_usec / 1000;
#elif defined(__STDC__) && __STDC_VERSION__ == 201112L
struct timespec timespec_value;
timespec_get(×pec_value,TIME_UTC);
return timespec_value.tv_sec * 1000LL + timespec_value.tv_nsec / 1000000;
#else
time_t current_time=time(NULL);
return current_time * 1000LL;
#endif
}
#endif //HELLOWORDC_TIME_UTILS_H
获取日历结构体
#include <time.h>
//获取日历结构体
time_t cur_time;
time(&cur_time);
struct tm *calender_time=localtime(&cur_time);
//年
printf("%d\n",calender_time->tm_year);
//月
printf("%d\n",calender_time->tm_mon);
//日
printf("%d\n",calender_time->tm_mday);
//时
printf("%d\n",calender_time->tm_hour);
//分
printf("%d\n",calender_time->tm_min);
//秒
printf("%d\n",calender_time->tm_sec);
时间结构体转换
//获取时间戳
time_t cur_time;
time(&cur_time);
//获取本地日历时间结构体
struct tm *calender_time=localtime(&cur_time);
calender_time->tm_sec=70;
//通过mktime函数将tm结构体转换time_t结构体类型
time_t return_time=mktime(&calender_time);
//获取GMT时间
struct tm *gm=gmtime(cur_time);
时间类型格式化字符串
time_t cur_time;
time(&cur_time);
struct tm *calender=localtime(&cur_time);
//Sun Sep 26 03:45:34 2021
char *strEgDate1=asctime(calender);
printf("%s \n",strEgDate1);
//时间结构体转换字符串,并且格式化时间
char strTime[20];
//格式化函数
strftime(strTime,20,"%Y-%m-%d %H:%M:%S",calender);
printf("%s \n",strTime);
字符串类型转时间
char *time="2021-09-26 00:03:12";
struct tm parseTime;
//字符串转时间
sscanf(time,"%4d-%2d-%2d %2d:%2d:%2d",
&parseTime.tm_year,
&parseTime.tm_mon,
&parseTime.tm_mday,
&parseTime.tm_hour,
&parseTime.tm_min,
&parseTime.tm_sec);
//年
printf("%d\n",parseTime.tm_year);
//月
printf("%d\n",parseTime.tm_mon);
//日
printf("%d\n",parseTime.tm_mday);
//时
printf("%d\n",parseTime.tm_hour);
//分
printf("%d\n",parseTime.tm_min);
//秒
printf("%d\n",parseTime.tm_sec);
两个时间差
time_t start_time=time(NULL);
time_t end_time=time(NULL);
//两个时间差
double diff=difftime(start_time,end_time);
printf("%f",diff);
两个时间毫秒差
clock_t start_time_c=clock();
clock_t end_time_c=clock();
//时间毫秒
printf("%f",(end_time_c-start_time_c)*1.0/CLOCKS_PER_SEC);
网友评论