c/c++ 时间函数总结 linux-转

本文详细介绍了 Linux 下 C/C++ 中关于时间的存储方式和常用时间函数,包括从1970年到现在经过了多少秒的存储方式、用结构体存储年月日时分秒的详细解释以及常用的时间函数如 asctime、ctime、mktime 等的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Linux c/c++关于时间函数的总结

很想花点时间整理下Linux c/c++关于时间函数,今天…

关于时间的存储

linux下存储时间常见的有两种存储方式,一个是1970年到现在经过了多少秒,一个是用一个结构来分别存储年月日时分秒的。

time_t 这种类型就是用来存储从1970年到现在经过了多少秒,要想更精确一点,可以用结构struct timeval,它精确到微妙。

struct timeval

{

   long tv_sec; /*秒*/

   long tv_usec; /*微秒*/

};

而直接存储年月日的是一个结构:

struct  tm

{

    inttm_sec;  /*秒,正常范围0-59, 但允许至61*/

    inttm_min;  /*分钟,0-59*/

    inttm_hour; /*小时, 0-23*/

    inttm_mday; /*日,即一个月中的第几天,1-31*/

    inttm_mon;  /*月, 从一月算起,0-11*/ 1+p->tm_mon;

    inttm_year;  /*年, 从1900至今已经多少年*/  1900+ p->tm_year;

    inttm_wday; /*星期,一周中的第几天, 从星期日算起,0-6*/

    inttm_yday; /*从今年1月1日到目前的天数,范围0-365*/

    int tm_isdst; /* 夏令时标识符,夏令时tm_isdst为正;不实行夏令时tm_isdst为0;*/

};

注:年份是从1900年起至今多少年,而不是直接存储如2013年,月份从0开始的,0表示一月,星期也是从0开始的, 0表示星期日,1表示星期一。

下面介绍一下我们常用的时间函数:

#include <time.h>

char *asctime(const struct tm* timeptr)

将结构中的信息转换为真实世界的时间,以字符串的形式显示

char *ctime(const time_t *timep)

将timep转换为真是世界的时间,以字符串显示,它和asctime不同就在于传入的参数形式不一


[cpp] view plaincopyprint?

  1. #include<iostream>                                                                                                 

  2. #include<ctime>                                                                                                      

  3. using namespace std;                                                                                                  

  4. int  main()                                                                                                           

  5. {    

  6.   time_t t;                                                                                                             

  7.   t=time(NULL);                                                                                                         

  8.   cout <<ctime(&t);                                                                                                     

  9.   return 0;   

  10. }       




double difftime(time_t time1, time_t time2)
返回两个时间相差的秒数

int stime(time_t *tp);

本函数用于设定电脑系统之日期与时间,传回值为0

格式化日期时间(strftime)

size_tstrftime(char *s, size_t maxsize, const char *fmt, const struct tm *t)

将t结构之资料依格式fmt方式设定给字串s,字串长度最长为maxsize,若转换错误则传回0,fmt之输出格式以ANSI方式为之。 下列为ANSI内定格式指定字及说明,使用在strftime内之格式。

%%:显示字元%

%a:星期之缩写

%A:星期之全名

%b:月份之缩写

%B:月份之全名

%c:日期与时间

%d:两位数之日(01 - 31)

%H:两位数之24小时制(00 - 23)

%I :两位数之12小时制(01 - 12)

%j:三位数之日数(001 - 366)

%m:两位数之月(1 - 12)

%M:两位数之分(00 - 59)

%p:代表AM或PM

%S:两位数之秒(00 - 59)

%U:两位数之星期数(00 - 53),以星期日为第一天

%w:星期之表示(0 - 6),0为星期日

%W:两位数之星期数(00 - 53),以星期一为第一天(00 - 53)

%x:日期, %X:时间, %y:两位数之年(00to 99)

%Y:西元年, %Z:时间区名称

 

类似于snprintf函数,我们可以根据format指向的格式字符串,将struct tm结构体中信息输出到s指针指向的字符串中,最多为max个字节。当然s指针指向的地址需提前分配空间,比如字符数组或者malloc开辟的堆空间

简单使用方法如下


[cpp] view plaincopyprint?

  1. #include<stdio.h>  

  2. #include<string.h>  

  3. #include<time.h>  

  4. int main( void )  

  5. {  

  6.     struct tm *newtime;  

  7.     char tmpbuf[128];  

  8.     time_t test;  

  9.     

  10. time(&test);  

  11.     newtime=localtime(&test);  

  12.     

  13. strftime(tmpbuf, 128, "Today is %A, day %d of %B in the year %Y.\n", newtime);  

  14.     printf(tmpbuf);  

  15.    

  16. return 0;  

  17. }  



char *_strtime(char *buf)

将现在时刻以HH:MM:SS方式输出放在buf内,字串至少9个Bytes长

char *_strtdate(char *buf);

取得目前PC系统日期及时间


[cpp] view plaincopyprint?

  1. #include<iostream>  

  2. #include<time>  

  3. using namespace std;  

  4. void main()  

  5. {  

  6. charsdate[9];  

  7. charstime[9];  

  8. _strdate(sdate);  

  9. _strtime(stime);  

  10. cout<<"目前日期:"<<sdate<<endl<<"现在时刻:"<<stime<<endl;  

  11. }  

支持windows



struct tm* gmtime(const time_t *timep)

将time_t表示的时间转换为没有经过时区转换的UTC时间(在计算机中看到的utc时间都是从(1970年01月01日 0:00:00)开始计算秒数的。所看到的UTC时间那就是从1970年这个时间点起到具体时间共有多少秒。),是一个struct tm结构指针

stuct tm* localtime(const time_t *timep)

和gmtime类似,但是它是经过时区转换的时间。

time_t mktime(struct tm* timeptr)

将structtm 结构的时间转换为从1970年至今的秒数

time_t time(time_t *t)

取得从1970年1月1日至今的秒数。 

参考代码:


[cpp] view plaincopyprint?

  1. #include<time.h>  

  2. int main()  

  3. {  

  4.     char *wday[] = {"Sun","Mon""Tue""Wed""Thu","Fri""Sat"};  

  5.     time_t timep;  

  6.     struct tm *p;  

  7.     

  8.     time(&timep); /*获得time_t结构的时间,UTC时间*/  

  9.     p = localtime(&timep); /*转换为struct tm结构的当地时间*/  

  10.     printf("%d/%d/%d ",<span style="color:#ff0000"> 1900 + p->tm_year, 1 +p->tm_mon, p->tm_mday);</span>  

  11.     printf("%s %d:%d:%d\n", wday[p->tm_wday], p->tm_hour,p->tm_min, p->tm_sec);  

  12.     return 0;  

  13. }  

clock函数

#include<time.h>

clock_tclock(void);                  

返回从程序开始运行到程序中调用clock()函数之间的CPU时钟计时单元数

例子如下:


[cpp] view plaincopyprint?

  1. #include<stdio.h>  

  2. #include<stdlib.h>  

  3. #include<time.h>  

  4. int main(void)  

  5. {  

  6.     long   loop = 10000000L;  

  7.     double duration;  

  8.     clock_t start, end;  

  9.     printf("Time to do %ld empty loops is", loop);  

  10.     start = clock();  

  11.     while(loop--)   ;  

  12.     end = clock();  

  13.     duration =(double)(end-start)/CLOCKS_PER_SEC;  

  14.     printf("%f seconds\n", duration);  

  15.     return(0);  

  16. }  




utime函数

更改文件的存取和修改时间

#include<time.h>

intutime(const char pathname, const struct utimbuf *times);

返回值:成功返回0,失败返回-1

times为空指针,存取和修改时间设置为当前时间


[cpp] view plaincopyprint?

  1. #include<stdio.h>  

  2. #include<time.h>  

  3. int main(int argc, char *argv[])  

  4. {  

  5.        if(argc < 2){  

  6.               fprintf(stderr, "Error:usging command file_path");  

  7.               exit(1);  

  8.        }  

  9.    

  10.        utime(argv[1], NULL);  

  11.    

  12.        return(0);  

  13. }  


编译、运行:


[plain] view plaincopyprint?

  1. $touch file_test  

  2. $ ls-al file_test  // 先创建一个文件file_test,查看一下他的创建时间  

  3. -rw-r--r--1 hongdy hongdy 3431 05-01 05:59 file_test  

  4. $ gccutime.c –o utime  

  5. $./utime file_test         

  6. $ ls-al file_test  

  7. -rw-r--r--1 hongdy hongdy 3431 05-01 06:00 file_test  

  8.    


settimeofday函数

设置目前时间

#include<sys/time.h>

#include<unistd.h>

int settimeofday ( const& nbspstruct timeval*tv,const struct timezone *tz);

函数说明  settimeofday()会把目前时间设成由tv所指的结构信息,当地时区信息则设成tz所指的结构。详细的说明请参考gettimeofday()。注意,只有root权限才能使用此函数修改时间。

返回值  成功则返回0,失败返回-1,错误代码存于errno。

 

错误代码  EPERM 并非由root权限调用settimeofday(),权限不够。

EINVAL时区或某个数据是不正确的,无法正确设置时间。

times为空指针,存取和修改时间设置为当前时间

/************************************************

设置操作系统时间

参数:*dt数据格式为"2013-10-20 20:30:30"

调用方法:

char*pt="2013-10-20 20:30:30";

SetSystemTime(pt);

**************************************************/


[cpp] view plaincopyprint?

  1. intSetSystemTime(char *dt)  

  2. {  

  3. structrtc_time tm;  

  4. structtm _tm;  

  5. structtimeval tv;  

  6. time_ttimep;  

  7. sscanf(dt,"%d-%d-%d %d:%d:%d", &tm.tm_year,  

  8. &tm.tm_mon,&tm.tm_mday,&tm.tm_hour,  

  9. &tm.tm_min,&tm.tm_sec);  

  10. _tm.tm_sec= tm.tm_sec;  

  11. _tm.tm_min= tm.tm_min;  

  12. _tm.tm_hour= tm.tm_hour;  

  13. _tm.tm_mday= tm.tm_mday;  

  14. _tm.tm_mon= tm.tm_mon - 1;  

  15. _tm.tm_year= tm.tm_year - 1900;  

  16.    

  17. timep= mktime(&_tm);  

  18. tv.tv_sec= timep;  

  19. tv.tv_usec= 0;  

  20. if(settimeofday(&tv, (struct timezone *) 0) < 0)  

  21. {  

  22. printf ("Setsystem datatime error!\n");  

  23. return -1;  

  24. }  

  25. return 0;  

  26. }  


gettimeofday函数取得目前的时间

#include<time.h>

intgettimeofday ( struct& nbsptimeval * tv , struct timezone * tz );

函数说明  gettimeofday()会把目前的时间有tv所指的结构返回,当地时区的信息则放到tz所指的结构中。

timeval结构定义为:

structtimeval{

longtv_sec; /*秒*/

longtv_usec; /*微秒*/

};

timezone结构定义为:

structtimezone{

inttz_minuteswest; /*和Greenwich时间差了多少分钟*/

inttz_dsttime; /*日光节约时间的状态*/

};

上述两个结构都定义在/usr/include/sys/time.h。tz_dsttime 所代表的状态如下

DST_NONE/*不使用*/

DST_USA/*美国*/

DST_AUST/*澳洲*/

DST_WET/*西欧*/

DST_MET/*中欧*/

DST_EET/*东欧*/

DST_CAN/*加拿大*/

DST_GB/*大不列颠*/

DST_RUM/*罗马尼亚*/

DST_TUR/*土耳其*/

DST_AUSTALT/*澳洲(1986年以后)*/

返回值  成功则返回0,失败返回-1,错误代码存于errno。附加说明EFAULT指针tv和tz所指的内存空间超出存取权限。

times为空指针,存取和修改时间设置为当前时间

 gettimeofday函数的例子


[cpp] view plaincopyprint?

  1. #include<sys/time.h>  

  2. #include<unistd.h>  

  3. main(){  

  4. structtimeval tv;  

  5. structtimezone tz;  

  6. gettimeofday(&tv , &tz);  

  7. printf(“tv_sec;%d\n”, tv,.tv_sec)  

  8. printf(“tv_usec;%d\n”,tv.tv_usec);  

  9. printf(“tz_minuteswest;%d\n”, tz.tz_minuteswest);  

  10. printf(“tz_dsttime,%d\n”,tz.tz_dsttime);  

  11. }  



[plain] view plaincopyprint?

  1. 编译、运行:  

  2. tv_usec:136996  

  3. tz_minuteswest:-540  

  4. tz_dsttime:0  

  5. tv_sec:974857339  

  6.           


timer_struct结构

struct timer_struct {

   unsigned long expires; //定时器被激活的时刻

void (*fn)(void); //定时器激活后的处理函数

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值