A time is usually displayed in the project. If the time is displayed as hour, minute, and second within today, it is displayed as year, month, and day.
A correct version is provided here:
# Include
# Include
Using namespace std; bool isw.day (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 Year % *. * d month % *. * D ", 1900, local-> tm_year +, local-> tm_mon + 1, 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 (is1_day (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 ;}
In the function, struct tm * localtime (const time_t *); the pointer returned is a global variable. If bool is1_day (long utc_time) is written as an example, what's the problem?
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;}
Here we declare curDate and argsDate as pointers. Running the program will find that the function always returns true. Why?
Because the pointer returned in struct tm * curDate = localtime (& timeCur); is a global variable, that is, curDate also points to this global variable.
In struct tm * argsDate = localtime (& utc_time);, the global variable pointed to by the amount pointer is returned. Therefore, argsDate and cur point to the same global variable, their memory areas are the same.
When localtime () is called for the second time, the value of the global variable is modified, and the curDate is also changed. Therefore, curDate = argsDate; therefore, the returned result is equal to true.