C++时间操作的汇总
1. 获取当前时间 time_t cur_time = time(NULL); 2. 把整数时间转为字符串时间 string GetStringTime(const time_t time) { struct tm *lptmNow; char sTime[sizeof("2010-12-21 12:39:56")]; #ifdef _WIN32 lptmNow = localtime(&time); #else struct tm tmNow; lptmNow = localtime_r(&time, &tmNow); #endif // 获得对应时间的日期 char szBuf[32]; snprintf(szBuf, sizeof(szBuf), "%04d年%02d月%02d日", lptmNow->tm_year + 1900, lptmNow->tm_mon + 1, lptmNow->tm_mday); int week = lptmNow->tm_wday; //获得星期几 int hour = lptmNow->tm_hour; //获得小时 int min = lptmNow->tm_min; //获得分钟 int sec = lptmNow->tm_sec; //获得秒 // 返回字符串时间 memset(sTime, 0, sizeof(sTime)); size_t length = strftime(sTime, sizeof(sTime), "%F %T", lptmNow); return string(sTime, length); } 3. 获得当前毫秒 unsigned long long GetCurMillSecond() { unsigned long long dwPreciseTime; #ifdef _WIN32 struct _timeb tbNow; _ftime(&tbNow); dwPreciseTime = (unsigned long long)tbNow.millitm; #else struct timeval tvNow; gettimeofday(&tvNow, NULL); dwPreciseTime = (unsigned long long)(tvNow.tv_sec*1000 + tvNow.tv_usec/1000); #endif return dwPreciseTime; } 4. 随机数种子初始化 void InitRand() { int Second; int USecond; #ifdef _WIN32 struct _timeb tbNow; _ftime(&tbNow); Second = (int)tbNow.time; USecond = tbNow.millitm; #else struct timeval tvNow; gettimeofday(&tvNow, NULL); Second = tvNow.tv_sec; USecond = tvNow.tv_usec; #endif srand(Second * USecond); } 5. 线程睡眠,单位为微妙 void USleep(unsigned long USeconds) { #ifdef _WIN32 Sleep(USeconds / 1000); #else struct timeval oDelay; oDelay.tv_sec = (unsigned long)USeconds / 1000000; oDelay.tv_usec = (unsigned long)USeconds % 1000000; select(0, 0, 0, 0, &oDelay); #endif } 6. 解析日期时间为整数时间 time_t ParseDateTime(const char* str) { struct tm tm = {}; #ifdef _XOPEN_SOURCE const char* end = strptime(str, "%F %T", &tm); if (end && end - str >= int(sizeof("2013-02-14 00:00:00") - 1)) return mktime(&tm); #else if (sscanf(str, "%u-%u-%u %u:%u:%u", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec ) == 6) { tm.tm_year -= 1900; tm.tm_mon -= 1; return mktime(&tm); } #endif return time_t(-1); }