C and C++ determine whether the incoming UTC time is the implementation method of the day

  • 2020-04-02 02:09:53
  • OfStack

Here's the correct version:


#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 years %*.*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("%sn",GetStringTime(utc_time).c_str());
    }else{
        printf("%sn",GetStringDate(utc_time).c_str());
    }

}
int main(){

    ShowTime(1389998142);
    ShowTime(time(NULL));

    return 0;
}

Struct tm *localtime(const time_t *); The returned pointer to a global variable, if the function bool IsInToday(long utc_time); What's the problem with writing it like this?


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;
}

CurDate and argsDate are declared as Pointers. If you run the program, you'll see that this function always returns true. Why?
Because in struct tm* curDate = localtime(&timeCur); The pointer returned in "is to a global variable that curDate also points to.
Struct tm* argsDate = localtime(&utc_time); So argsDate and cur point to the same global variable, and their memory area is the same.
The second time localtime() is called, the value of the global variable is changed, so curDate == argsDate; So the value returned is equal to true.


Related articles: