在項目中經常會顯示一個時間,如果這個時間在今日內就顯示為時分秒,否則顯示為年月日。
這裡先給出一個正確的版本:
#include#include using namespace std; bool IsInToday(long utc_time){ time_t timeCur = time(NULL); struct tm curDate = *localtime(&timeCur); struct tm argsDate = *localtime(&utc_time); if (argsDate.tm_year == curDate.tm_year && argsDate.tm_mon == curDate.tm_mon && argsDate.tm_mday == curDate.tm_mday){ return true; } return false; } std::string GetStringDate(long utc_time){ struct tm *local = localtime(&utc_time); char strTime[50]; sprintf(strTime,"%*.*d年%*.*d月%*.*d日", 4,4,local->tm_year+1900, 2,2,local->tm_mon+1, 2,2,local->tm_mday); return strTime; } std::string GetStringTime(long utc_time){ struct tm local = *localtime(&utc_time); char strTime[50]; sprintf(strTime,"%*.*d:%*.*d:%*.*d", 2,2,local.tm_hour, 2,2,local.tm_min, 2,2,local.tm_sec); return strTime; } void ShowTime(long utc_time){ if (IsInToday(utc_time)){ printf("%s\n",GetStringTime(utc_time).c_str()); }else{ printf("%s\n",GetStringDate(utc_time).c_str()); } } int main(){ ShowTime(1389998142); ShowTime(time(NULL)); return 0; }
在函數中struct tm *localtime(const time_t *);中返回的指針指向的是一個全局變量,如果把函數bool IsInToday(long utc_time);寫成樣,會有什麼問題呢?
bool IsInToday(long utc_time){ time_t timeCur = time(NULL); struct tm* curDate = localtime(&timeCur); struct tm* argsDate = localtime(&utc_time); if (argsDate->tm_year == curDate->tm_year && argsDate->tm_mon == curDate->tm_mon && argsDate->tm_mday == curDate->tm_mday){ return true; } return false; }