Here is a correct version:
Copy Code code as follows:
#include <iostream>
#include <time.h>
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 month%*.*d Day",
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 the TM *localtime (const time_t *) in the function, the pointer returned in is a global variable, and if the function is bool Isintoday (long Utc_time), what's the problem?
Copy Code code as follows:
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 the curdate and Argsdate are declared as pointers. Running the program will find that the function returned is always ture, why?
Because the pointer returned in struct tm* curdate = localtime (&timecur) is a global variable, that is, Curdate also points to the global variable.
In the struct tm* argsdate = localtime (&utc_time); The return pointer also points to this global variable, so argsdate and cur point to the same global variable whose memory area is the same block.
When LocalTime () is invoked the second time, the value of the global variable is modified, and the curdate is changed, so curdate = = Argsdate is returned, so the resulting balance equals true.