常用C语言time时间函数

常见的时间函数有time( )、ctime( )、gmtime( )、localtime( )、mktime( )、asctime( )、difftime( )、gettimeofday( )、settimeofday( )
其中,gmtime和localtime函数差不多,只是localtime函数会按照时区输出,而gmtime是用于输出0时区的
常见的时间类型有
time_t
struct timeval(设置时间函数settimeofday( )与获取时间函数gettimeofday( )均使用该事件类型作为传参。)
struct tm,
struct timespec
使用gmtime( )和localtime( )可将time_t时间类型转换为tm结构体;
使用mktime( )将tm结构体转换为time_t时间类型;
使用asctime( )将struct tm转换为字符串形式。

//各个结构体的定义
struct tm{  
    int tm_sec; /*秒 - 取值区间为[0, 59]*/  
    int tm_min; /*分 - 取值区间为[0, 59]*/  
    int tm_hour; /*时 - 取值区间为[0, 23]*/  
    int tm_mday; /*日 - 取值区间为[1, 31]*/  
    int tm_mon; /*月份 - 取值区间为[0, 11]*/  
    int tm_year; /*年份 - 其值为1900年至今年数*/  
    int tm_wday; /*星期 - 取值区间[0, 6],0代表星期天,1代表星期1,以此类推*/  
    int tm_yday; /*从每年的1月1日开始的天数-取值区间为[0, 365],0代表1月1日*/  
    int tm_isdst; /*夏令时标识符,使用夏令时,tm_isdst为正,不使用夏令时,tm_isdst为0,不了解情况时,tm_isdst为负*/  
};  
Struct tmieval{  
    time_t tv_sec; /*秒s*/  
    suseconds_t tv_usec; /*微秒us*/  
}; 
struct timespec{  
    time_t tv_sec; /*秒s*/  
    long tv_nsec; /*纳秒ns*/  
};  

现在我们来看一下使用这些函数的程序
首先是time()函数的使用

[root@bogon time]# cat time.c 
#include<time.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
    time_t seconds,sec,time1,time2;
    struct tm *mytm,gettm;
    seconds=time(NULL);
    mytm=localtime(&seconds);//localtime的参数为time_t类型
    sec=mktime(mytm);//mktime参数为结构体tm类型
    time1=time(NULL);//time参数类型为time_t类型,或者为NULL也可以
    sleep(1);//因为要difftime,所以让time1和time2不同
    time2=time(NULL);
    printf("use time: %ld
",seconds);
    printf("use ctime: %s",ctime(&seconds));//ctime的类型也为time_t类型
    printf("use gmtime: %d-%d-%d
",(mytm->tm_year)+1900,(mytm->tm_mon)+1,mytm->tm_mday);
    printf("use mktime :%ld
",sec);
    printf("use asctime: %s",asctime(mytm));//跟ctime功能差不多,只是它的参数是结构体tm类型的
    printf("use difftime: %lf
",difftime(time1,time2));//计算time1-time2
    return 0;
}
[root@bogon time]# gcc time.c 
[root@bogon time]# ./a.out
use time: 1495946001
use ctime: Sat May 27 21:33:21 2017
use gmtime: 2017-5-27
use mktime :1495946001
use asctime: Sat May 27 21:33:21 2017
use difftime: -1.000000
[root@bogon time]# 

“`
参考文章传送门http://blog.csdn.net/water_cow/article/details/7521567

原文地址:https://www.cnblogs.com/biaopei/p/7730623.html