- 由于自己實(shí)際工作學(xué)習(xí)中沒怎么用時(shí)間和日期的函數(shù),在看Unix環(huán)境高級(jí)編程6.10節(jié)和Python的time模塊時(shí),總感覺這些東西總是連不成串。
還是從C開始理一理吧。翻翻C標(biāo)準(zhǔn)(C++中的東西我看不懂),相關(guān)的也就是time.h這個(gè)東西了。
宏
|
NULL CLOCKS_PER_SEC
|
類型
|
size_t clock_t time_t
|
結(jié)構(gòu)體
|
tm
|
函數(shù)
|
asctime clock difftime localtime strftime
ctime gmtime mktime time
|
走馬觀花
暫時(shí)拋開和clock相關(guān)的東西。只看字面上和time直接相關(guān)的東西。

獲取時(shí)間
如何從操作系統(tǒng)獲取時(shí)間呢?
time_t time(time_t *t);
該函數(shù)返回從某個(gè)時(shí)間點(diǎn)(epoch)到現(xiàn)在為止所經(jīng)過的秒數(shù)。(這個(gè)數(shù)稱為日歷時(shí)間) 比如:
1319206097
- (一般情況下這個(gè)時(shí)間點(diǎn)都是公元1970年1月1日0時(shí),但是微軟的C/C++編譯器版本7中用的卻是1899年12月31日0時(shí),注意,編譯器的版本不是MVSC的版本,比如MSVC2010也叫VC9,但對(duì)應(yīng)的編譯器版本是16)
這個(gè)數(shù)字對(duì)人來說可真不友好。比如上面這個(gè)對(duì)應(yīng)的具體日期是什么,如果不是我寫的我還真不知道
轉(zhuǎn)成字符串
char *ctime(const time_t *timep);
我們知道,同一時(shí)刻各個(gè)時(shí)區(qū)的時(shí)間是不同的。這個(gè)函數(shù)會(huì)考慮當(dāng)前的時(shí)區(qū)(通過環(huán)境變量TZ)
Fri Oct 21 22:08:17 2011\n\0
這下好看多了,但還是很不夠...
分解時(shí)間,結(jié)構(gòu)體 tm
我們可以將日歷時(shí)間,轉(zhuǎn)成包含時(shí)分秒等信息的結(jié)構(gòu)體。這樣處理起來就方面多了。
struct tm *gmtime(const time_t *timep);
struct tm *localtime(const time_t *timep);
- 注意:返回的tm結(jié)構(gòu)體的指針,指向的是其內(nèi)部的一個(gè)靜態(tài)tm結(jié)構(gòu)體變量。
gmtime
格林威治時(shí)間
|
localtime
本地時(shí)間(東8區(qū))
|
|
17
|
17
|
秒
|
8
|
8
|
分
|
14
|
22
|
時(shí)
|
21
|
21
|
21日
|
9
|
9
|
10月(從0開始算)
|
111
|
111
|
2011年(從1900開始)
|
5
|
5
|
周五
|
293
|
293
|
一年中的第293天
|
0
|
0
|
不是夏時(shí)制
|
要從分解時(shí)間轉(zhuǎn)換會(huì)日歷時(shí)間,則使用
time_t mktime(struct tm *tm);
轉(zhuǎn)成字符串2
前面的ctime可以從日歷時(shí)間轉(zhuǎn)成字符串,那么從分解時(shí)間如何轉(zhuǎn)成字符串呢?
char *asctime(const struct tm *tm);
比如:前面的gmtime和localtime得到的分解時(shí)間,分別對(duì)應(yīng)
Fri Oct 21 14:24:34 2011
Fri Oct 21 22:24:34 2011
不過這個(gè)東西太死板了吧,想自定義字符串怎么辦?
size_t strftime(char *s, size_t max, const char *format,
const struct tm *tm);
和printf類似,有一大堆轉(zhuǎn)換符可用,這樣一來,我們可以得到
Fri
Friday
2011-10-21
10:24:34 PM
...
類型
簡單羅列一下:
time_t
一個(gè)整數(shù)類型,但具體的范圍和精度是由編譯器實(shí)現(xiàn)所定義的。
struct tm
結(jié)構(gòu)體tm 表示 分解時(shí)間(broken-down time)
struct tm {
|
|
int tm_sec;
|
|
int tm_min;
|
/* 分鐘: [0 - 59] */
|
int tm_hour;
|
/* 小時(shí): [0 - 23] */
|
int tm_mday;
|
/* 日: [1 - 31] */
|
int tm_mon;
|
/* 月: [0 - 11] */
|
int tm_year;
|
/* 年: 從1900年開始算起 */
|
int tm_wday;
|
/* 星期X: [0 - 6] */
|
int tm_yday;
|
/* 一年中第X天: [0 - 365] */
|
int tm_isdst;
|
/* 夏時(shí)制標(biāo)記: <0, 0, >0 */
|
};
|
|
夏時(shí)值,即:日光節(jié)約時(shí)制(Daylight Saving Time)
clock_t
clock_t clock(void);
返回程序自開始執(zhí)行到目前為止所占用的處理機(jī)時(shí)間。如果處理機(jī)時(shí)間不可使用,那么返回-1。clock()/CLOCKS_PER_SEC是以秒為單位表示的時(shí)間。
其他
Unix
在Unix下,與time()相比,
int gettimeofday(struct timeval *tv, struct timezone *tz);
可以獲得更高的分辨率(最高為微秒)。
QThread::sleep()在unix下的實(shí)現(xiàn)使用該函數(shù)。
python的time模塊中的time()/sleep()也使用該函數(shù)。
locale
函數(shù)strftime()生成的字符串受locale中的LC_TIME影響
|