1、字符串到time_t的轉換
- BOOL GetStrFromTime(time_t iTimeStamp, char *pszTime)
- {
- tm *pTmp = localtime(&iTimeStamp);
- if (pTmp == NULL)
- {
- return FALSE;
- }
- sprintf(pszTime, "%d-%d-%d %d:%d:%d", pTmp->tm_year + 1900, pTmp->tm_mon + 1, pTmp->tm_mday, pTmp->tm_hour, pTmp->tm_min, pTmp->tm_sec);
- return TRUE;
- }
這裡的time_t可以傳入一個unsigned int類型的參數,其表示的含義是1970.1.1 0:0:0開始計時的秒數,返回字符串結構如“2011-08-05 00:00:00”。
2、字符串到tm到time_t的轉換
- unsigned int GetTimeStampByStr( const char* pDate, int32 iNameSize )
- {
- const char* pStart = pDate;
-
- char szYear[5], szMonth[3], szDay[3], szHour[3], szMin[3], szSec[3];
-
- szYear[0] = *pDate++;
- szYear[1] = *pDate++;
- szYear[2] = *pDate++;
- szYear[3] = *pDate++;
- szYear[4] = 0x0;
-
- ++pDate;
-
- szMonth[0] = *pDate++;
- szMonth[1] = *pDate++;
- szMonth[2] = 0x0;
-
- ++pDate;
-
- szDay[0] = *pDate++;
- szDay[1] = *pDate++;
- szDay[2] = 0x0;
-
- ++pDate;
-
- szHour[0] = *pDate++;
- szHour[1] = *pDate++;
- szHour[2] = 0x0;
-
- ++pDate;
-
- szMin[0] = *pDate++;
- szMin[1] = *pDate++;
- szMin[2] = 0x0;
-
- ++pDate;
-
- szSec[0] = *pDate++;
- szSec[1] = *pDate++;
- szSec[2] = 0x0;
-
- tm tmObj;
-
- tmObj.tm_year = atoi(szYear)-1900;
- tmObj.tm_mon = atoi(szMonth)-1;
- tmObj.tm_mday = atoi(szDay);
- tmObj.tm_hour = atoi(szHour);
- tmObj.tm_min = atoi(szMin);
- tmObj.tm_sec = atoi(szSec);
- tmObj.tm_isdst= -1;
-
- return mktime(&tmObj);
- }
這裡是完成將諸如"2011-01-01 00:00:00"格式的日期字符串轉換為時間戳,更多關於<time.h>中提供的函數很簡單,網上資料也很多,故不再贅述。