C语言time.h的使用

    以前经常在程序中获取系统时间,计算时间,但是每次都是到网上临时找来一些资料对付过去,今天就索性整理一下。

    关于C语言time.h的一些应用。

    clock_t clock(void);    //得到从进程启动到此次函数调用的累计的时钟滴答数。每秒包含CLOCKS_PER_SEC(time.h中定义的常量,一般为1000,貌似linux下为1000000)个时钟滴答。时钟滴答数用数据类型clock_t表示。clock_t类型一般是32位整数类型。

    time_t time(time_t* timer);    //得到从标准计时点(一般是1970年1月1日0时0秒)到当前时间的秒数。日历时间用数据类型time_t表示。time_t类型实际上一般是32位或64位整数类型。

    分解时间同结构体类型表示tm表示:

    struct tm

    {

        int tm_hour;    //时    0~23

        int tm_isdst;    //夏令时是否开启    开启(> 0),关闭(= 0),未知(< 0)

        int tm_mday; //日    0~31

        int tm_min;    //分    0~59

        int tm_mon;   //月    0~11

        int tm_sec;    //秒    0~60(60为天文学中定义的闰秒)

        int tm_wday;  //星期,从星期天计    0~6

        int tm_yday;   //本年经过的天数    0~365

        int tm_year;    //从1900年起经过的年数    

    };    

    struct tm* gmtime(const time_t* timer);      //从日历时间time_t到分解时间tm的转换。函数返回的是一个静态分配的tm结构存储空间,该存储空间被gmtime,localtime与ctime函数所共用. 这些函数的每一次调用会覆盖这块tm结构存储空间的内容。

    struct tm* gmtime_r(const time_t* timer , struct tm*result);    //该函数是gmtime函数的线程安全版本

    struct tm* localtime(const time_t* timer);    //从日历时间time_t到分解时间tm的转换,即结果数据已经调整到本地时区与夏令时。

    time_t mktime(struct tm* ptm);    //从分解时间tm到日历时间time_t的转换。

    time_t timegm(struct tm* brokentime);    //从分解时间tm(被视作UTC时间,不考虑本地时区设置)到日历时间time_t的转换。该函数较少被使用。        

    double difftime(time_t timer2, time_t timer1);    //比较两个日历时间,返回double类型的秒数差。似乎用处不大,time_t可以直接相减

   

    以下是几个把日期数据按常用格式输出的函数:

    char *asctime(const struct tm* tmptr);    //把分解时间tm输出到字符串,结果的格式为"Www Mmm dd hh:mm:ss yyyy",即“周几 月份数 日数 小时数:分钟数:秒钟数 年份数”。函数返回的字符串为静态分配,长度不大于26,与ctime函数共用。函数的每次调用将覆盖该字符串内容。

    char* ctime(const time_t* timer);    //把日历时间time_t timer输出到字符串,输出格式与asctime函数一样。

    size_t strftime(char* s, size_t n, const char* format, const struct tm* tptr);    //把分解时间tm转换为自定义格式的字符串,类似于常见的字符串格式输出函数sprintf。

    char * strptime(const char* buf, const char* format, struct tm* tptr);    //strftime的逆操作,把字符串按照自定义的格式转换为分解时间tm。恩恩……这个函数还是比较有意思的。

    其中上面的自定义格式字符串类型有自己的格式命令符,相当多,请读者自己查阅。

    下面是我写的代码:

    //取按下回车前后的系统时间,并计算时间差   

  1 #include
  2 #include
  3 int main()
  4 {
  5     time_t now1,now2,d,h,m,s,t;
  6     struct tm *tnow1,*tnow2;
  7     time(&now1);    tnow1=localtime(&now1);
  8     printf("%s\n",asctime(tnow1));
  9     getchar();//等待回车
 10     time(&now2);    tnow2=localtime(&now2);
 11     printf("%s\n",asctime(tnow2));
 12     t=now2-now1;    d=t/86400;
 13     t%=86400;   h=t/3600;
 14     t%=3600;    m=t/60; s=t%60;
 15     printf("Time Difference: %d day  %d hour  %d mintues  %d seconds\n",d,h,m,s);
 16     return 0;
 17 }

      运行结果:

    C语言time.h的使用_第1张图片   

转载于:https://my.oschina.net/llmm/blog/89927

你可能感兴趣的:(C语言time.h的使用)