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結構指針,待轉換的時間。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章