C/C++判斷傳入的UTC時間是否當(dāng)天的實現(xiàn)方法
這里先給出一個正確的版本:
#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月%*.*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;
}
在函數(shù)中struct tm *localtime(const time_t *);中返回的指針指向的是一個全局變量,如果把函數(shù)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;
}
這里把curDate和argsDate聲明成了指針。運行程序就會發(fā)現(xiàn),這個函數(shù)返回的總是ture,為什么呢?
因為在struct tm* curDate = localtime(&timeCur);中返回的指針指向的是一個全局變量,即curDate也指向這個全局變量。
在struct tm* argsDate = localtime(&utc_time);中返回額指針也指向的這個全局變量,所以argsDate和cur指向的是同一個全局變量,他們的內(nèi)存區(qū)域是同一塊。
在第二次調(diào)用localtime()時,修改了全局變量的值,curDate也隨之改變,因此curDate == argsDate;所以返回的結(jié)果衡等于true。
相關(guān)文章
詳解C++中typedef 和 #define 的區(qū)別
這篇文章主要介紹了C++中typedef 與 #define 的區(qū)別,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09數(shù)據(jù)結(jié)構(gòu) 雙機(jī)調(diào)度問題的實例詳解
這篇文章主要介紹了數(shù)據(jù)結(jié)構(gòu) 雙機(jī)調(diào)度問題的實例詳解的相關(guān)資料,雙機(jī)調(diào)度問題,又稱獨立任務(wù)最優(yōu)調(diào)度:用兩臺處理機(jī)A和B處理n個作業(yè)的實例,需要的朋友可以參考下2017-08-08Visual?Studio2022報錯無法打開源文件?"openssl/conf.h"解決方法
這篇文章主要介紹了Visual?Studio2022報錯無法打開源文件"openssl/conf.h"解決方式,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07C語言進(jìn)階輸入輸出重定向與fopen函數(shù)使用示例詳解
這篇文章主要為大家介紹了C語言進(jìn)階輸入輸出重定向與fopen函數(shù)的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-02-02