c++ time function


  1. //Convert the numeric time to string time
  2. BOOL GetStrFromTime(time_t iTimeStamp, char *pszTime)  
  3. {  
  4.    tm *pTmp = localtime(&iTimeStamp);  
  5.    if (pTmp == NULL)  
  6.    {  
  7.       return FALSE;  
  8.    }  
  9.    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);  
  10.    return TRUE;  
  11. }  

2. Precise delay

GetTickCount()

      The calling function needs to include windows.h. The obtained time is accurate to milliseconds when the system is running. The test program is as follows: [c-shap] view pla 

  1. #include <iostream>  
  2. #include <windows.h>  
  3. usingnamespace std;   
  4. intmain  ()  
  5. {  
  6.     double start = GetTickCount();  
  7.     Sleep(1000);  
  8.     double  end=GetTickCount();  
  9.     cout << "GetTickCount:" << end-start << endl;  
  10.         return 0;  
  11. }  

3. String to Number

  1. unsigned int GetTimeStampByStr( const char* pDate, int32 iNameSize )   
  2. {  
  3.    const char* pStart = pDate;  
  4.      
  5.    char szYear[5], szMonth[3], szDay[3], szHour[3], szMin[3], szSec[3];  
  6.      
  7.    szYear[0]   = *pDate++;  
  8.    szYear[1]   = *pDate++;  
  9.    szYear[2]   = *pDate++;  
  10.    szYear[3]   = *pDate++;  
  11.    szYear[4]   = 0x0;  
  12.      
  13.    ++pDate;  
  14.      
  15.    szMonth[0]  = *pDate++;  
  16.    szMonth[1]  = *pDate++;  
  17.    szMonth[2]  = 0x0;  
  18.      
  19.    ++pDate;  
  20.      
  21.    szDay[0]    = *pDate++;   
  22.    szDay[1]    = *pDate++;  
  23.    szDay[2]    = 0x0;  
  24.      
  25.    ++pDate;  
  26.      
  27.    szHour[0]   = *pDate++;  
  28.    szHour[1]   = *pDate++;  
  29.    szHour[2]   = 0x0;  
  30.      
  31.    ++pDate;  
  32.      
  33.    szMin[0]    = *pDate++;  
  34.    szMin[1]    = *pDate++;  
  35.    szMin[2]    = 0x0;  
  36.      
  37.    ++pDate;  
  38.      
  39.    szSec[0]    = *pDate++;  
  40.    szSec[1]    = *pDate++;  
  41.    szSec[2]    = 0x0;  
  42.      
  43.    tm tmObj;  
  44.      
  45.    tmObj.tm_year = atoi(szYear)-1900;  
  46.    tmObj.tm_mon  = atoi(szMonth)-1;  
  47.    tmObj.tm_mday = atoi(szDay);  
  48.    tmObj.tm_hour = atoi(szHour);  
  49.    tmObj.tm_min  = atoi(szMin);  
  50.    tmObj.tm_sec  = atoi(szSec);  
  51.    tmObj.tm_isdst= -1;  
  52.      
  53.    return mktime(&tmObj);  
  54. }  

4.获取当前时间

  1. #include <iostream>  
  2. #include <windows.h>  
  3. usingnamespace std;   
  4. intmain  ()  
  5. {  
  6.     SYSTEMTIME start; //windows.h中  
  7.     GetLocalTime(&start); //The same effect as the tm structure of time.h  
  8.     cout<< start.year << endl;  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325904322&siteId=291194637