linux C语言 time.h,C语言time.h的使用

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

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

clock_tclock(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_tmktime(struct tm*ptm);   //从分解时间tm到日历时间time_t的转换。

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

doubledifftime(time_ttimer2, time_ttimer1);   //比较两个日历时间,返回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_tstrftime(char*s, size_tn, 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 }

运行结果:

e4a75a59b8aab216e6eb1f80cf71cf8f.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值