歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux C時間函數 time_t struct tm

Linux C時間函數 time_t struct tm

日期:2017/3/1 9:35:11   编辑:Linux編程

Linux C時間函數 time_t struct tm

#include<time.h>

關於時間的類型:

time_t long型,表示從1970年1月1日到現在經過的秒數。

struct tm {
int tm_sec; /* 秒 – 取值區間為[0,59] */
int tm_min; /* 分 - 取值區間為[0,59] */
int tm_hour; /* 時 - 取值區間為[0,23] */
int tm_mday; /* 一個月中的日期 - 取值區間為[1,31] */
int tm_mon; /* 月份(從一月開始,0代表一月) - 取值區間為[0,11] */
int tm_year; /* 年份,其值等於實際年份減去1900 */
int tm_wday; /* 星期 – 取值區間為[0,6],其中0代表星期天,1代表星期一,以此類推 */
int tm_yday; /* 從每年的1月1日開始的天數 – 取值區間為[0,365],其中0代表1月1日,1代表1月2日

};

一般用time_t:定義 time_t now;通過now =time(NULL)返回當前的時間(秒數),time函數形式是“time_t time(time_t*)”,也可以像這樣獲取“time(&now)”。用戶看這個大的Long型數據是沒啥意義,一般通過這個函數先後得到時間計算時間差比較方便。srand(unsigned(time(NULL))獲取種子的用法運用的就是這個秒數。

想清晰得得到現在的年月日信息,就不能通過這個time_t了,需要用struct tm來顯示,而將time_t和struct tm轉換的函數就是localtime(time_t*),返回一個struct tm*類型,注意是指針類型。然後可以得到tm中的成員,如上,皆為整形。

如果想直接獲取時間的字符串。

用 char * asctime(const struct tm * timeptr);根據struct tm結構

或者用 char* ctime(time_t* t);//根據time_t

輸出的形式都是像這樣 "Tue Jan 6 13:53:16 2015 "

注意思考為什麼我們只需要定義一個struct tm*的指針,並沒有申請空間,卻可以獲取其成員?因為locatime返回指針是一個靜態變量的地址。同樣asctime也是同樣原理。

------------------------------分割線------------------------------

C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm

讀C++ Primer 之構造函數陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm

讀C++ Primer 之智能指針 http://www.linuxidc.com/Linux/2011-08/40177.htm

讀C++ Primer 之句柄類 http://www.linuxidc.com/Linux/2011-08/40175.htm

將C語言梳理一下,分布在以下10個章節中:

  1. Linux-C成長之路(一):Linux下C編程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
  2. Linux-C成長之路(二):基本數據類型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
  3. Linux-C成長之路(三):基本IO函數操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
  4. Linux-C成長之路(四):運算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
  5. Linux-C成長之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
  6. Linux-C成長之路(六):函數要義 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
  7. Linux-C成長之路(七):數組與指針 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
  8. Linux-C成長之路(八):存儲類,動態內存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
  9. Linux-C成長之路(九):復合數據類型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
  10. Linux-C成長之路(十):其他高級議題

Copyright © Linux教程網 All Rights Reserved