C/C++时间处理函数

C time库中提供了几个时间处理的函数:

获取时间

clock 获取程序从开始到调用clock硬件滴答数
difftime 获取两个时间的差
time 获取当前时间

转换时间

mktime 将tm结构转换成time_t
asctime 将tm结构转换成string
ctime 将time_t转换成string
gmtime 将time_t转换成tm结构(UTC时间)
localtime 将time_t转换成tm结构(本地时间)
strftime 将时间格式化成string

函数说明:

1、clock

原型:clock_t  clock ( void );

说明:返回自程序开始运行到调用clock时,硬件滴答的次数。宏CLOCKS_PER_SEC给出了每秒钟硬件滴答次数。

返回值:成功,返回硬件滴答次数;失败,返回-1。


2、difftime

原型:double difftime ( time_t time2, time_t time1 );

参数:time1,time2要计算时间差的两个时间,time1在time2前。

说明:计算time1和time2之间的相差的秒数。

返回值:返回(time2-time1)的秒数。


3、time

原型:time_t time ( time_t * timer );

参数:timer,time_t结构指针,存放当前日历时间。

说明:获取当前的日历时间。

返回值:返回当前日历时间;失败,返回-1。


4、mktime

原型:time_t mktime ( struct tm * timeptr );

参数:timerptr,tm结构指针

说明:mktime()用来将参数timeptr所指的tm结构数据转换成从公元1970年1月1日0时0分0 秒算起至今的UTC时间所经过的秒数。

返回值:返回经过的秒数。


5、asctime

原型:char * asctime ( const struct tm * timeptr );

参数:timerptr,tm结构指针

说明:将日期和时间转换成字符串。

返回值:字符串化的时间。


6、ctime

原型:char * ctime ( const time_t * timer );

参数:timer,time_t指针,存放从公元1970年1月1日0时0分0 秒算起至今的UTC时间所经过的秒数。

说明:将time_t时间转换成string,string格式如下:

Www Mmm dd hh:mm:ss yyyy

其中,Www,星期几;Mmm,月份(简写);dd,月份中的某一天;hh:mm:ss,具体时间;yyyy,年份。


7、gmtime

原型:struct tm * gmtime ( const time_t * timer );

参数:timer,time_t指针,存放从公元1970年1月1日0时0分0 秒算起至今的UTC时间所经过的秒数。

说明:将time_t时间转换成UTC时间的tm结构。


8、localtime

原型:struct tm * localtime ( const time_t * timer );

参数:timer,time_t指针,存放从公元1970年1月1日0时0分0 秒算起至今的UTC时间所经过的秒数。

说明:将time_t时间转换成本地时间的tm结构。


9、strftime

原型:size_t strftime ( char * ptr, size_t maxsize, const char * format, const struct tm * timeptr );

参数:ptr,存放转换结果的字符串指针;

            maxsize,复制到ptr的最大字符个数;

            format,格式化字符串,以%开始,格式说明如下:

 

specifier Replaced by Example
%a Abbreviated weekday name * Thu
%A Full weekday name * Thursday
%b Abbreviated month name * Aug
%B Full month name * August
%c Date and time representation * Thu Aug 23 14:55:02 2001
%d Day of the month (01-31) 23
%H Hour in 24h format (00-23) 14
%I Hour in 12h format (01-12) 02
%j Day of the year (001-366) 235
%m Month as a decimal number (01-12) 08
%M Minute (00-59) 55
%p AM or PM designation PM
%S Second (00-61) 02
%U Week number with the first Sunday as the first day of week one (00-53) 33
%w Weekday as a decimal number with Sunday as 0 (0-6) 4
%W Week number with the first Monday as the first day of week one (00-53) 34
%x Date representation * 08/23/01
%X Time representation * 14:55:02
%y Year, last two digits (00-99) 01
%Y Year 2001
%Z Timezone name or abbreviation CDT
%% A % sign %
* The specifiers whose description is marked with an asterisk (*) are locale-dependent.

timerptr,tm结构指针,待转换的时间。

说明:将日历时间转换成字符串。



此文章来自于【http://blog.csdn.net/isgray/article/details/6857728】

你可能感兴趣的:(时间函数)