在處理時間時用到了localtime這個函數,將一個UTC時間轉為本地時間:
[cpp]
#include <time.h>
time_t tmNow = time(NULL);
tm *ptmNow = localtime(&tmNow); //從tm結構體中可以取到年月日時分秒等值。
這裡localtime返回了一個tm指針,空間是由localtime自己控制的,所以如果連續調用這個函數會有問題。
很多時候我們會同時處理兩個時間,例如表示時間段的【起始時間】【結束時間】,代碼如下:
[cpp]
time_t tmBegin = 1351118531; //2012-10-25 06:42:11
time_t tmEnd = 1351218731; //2012-10-26 10:32:11
tm* ptmBegin = localtime(&tmBegin );
tm* ptmEnd = localtime(&tmEnd );//第二次調用會修改上次調用的tm結構體,若上次的數據未保存則會丟失
//tm* ptm3 = gmtime(&tmEnd ); //效果同上條語句,也會重寫之前的數據
char ctmBegin1[26], ctmEnd[26];
strftime(ctmBegin, 26, "%Y%m%d%H%M%S", ptmBegin); //這裡輸出的將是tmEnd的時間值
strftime(ctmEnd, 26, "%Y%m%d%H%M%S", ptmEnd);
/*MSDN中有相關說明:
Both the 32-bit and 64-bit versions ofgmtime, mktime, mkgmtime, and localtimeall
use a single tm structure per thread for the conversion. Each call to one of these
routines destroys the result of the previous call.
*/
所以要記住,一旦調用了localtime函數,應該馬上取出tm結構中的內容:
[cpp]
time_t tmBegin = 1351118531; //2012-10-25 06:42:11
time_t tmEnd = 1351218731; //2012-10-26 10:32:11
char ctmBegin1[26], ctmEnd[26];
tm* ptmBegin = localtime(&tmBegin );
strftime(ctmBegin, 26, "%Y%m%d%H%M%S", ptmBegin);
tm* ptmEnd = localtime(&tmEnd );
strftime(ctmEnd, 26, "%Y%m%d%H%M%S", ptmEnd);
//tm* ptm3 = gmtime(&tmEnd );