C/C++判斷傳入的UTC時間是否當天的實現(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指向的是同一個全局變量,他們的內存區(qū)域是同一塊。
在第二次調用localtime()時,修改了全局變量的值,curDate也隨之改變,因此curDate == argsDate;所以返回的結果衡等于true。
欄 目:C語言
下一篇:linux安裝mysql和使用c語言操作數(shù)據(jù)庫的方法 c語言連接mysql
本文標題:C/C++判斷傳入的UTC時間是否當天的實現(xiàn)方法
本文地址:http://www.jygsgssxh.com/a1/Cyuyan/3817.html
您可能感興趣的文章
- 04-02c語言沒有round函數(shù) round c語言
- 01-10如何判斷一個數(shù)是否為2的冪次方?若是,并判斷出來是多少次方
- 01-10深入理解C++中常見的關鍵字含義
- 01-10使用C++實現(xiàn)全排列算法的方法詳解
- 01-10如何判斷一個數(shù)是否為4的冪次方?若是,并判斷出來是多少次方
- 01-10c++中inline的用法分析
- 01-10用C++實現(xiàn)DBSCAN聚類算法
- 01-10全排列算法的非遞歸實現(xiàn)與遞歸實現(xiàn)的方法(C++)
- 01-10C++大數(shù)模板(推薦)
- 01-10淺談C/C++中的static與extern關鍵字的使用詳解


閱讀排行
本欄相關
- 04-02c語言函數(shù)調用后清空內存 c語言調用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調用函數(shù)求fibo C語言調用函數(shù)求
隨機閱讀
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10delphi制作wav文件的方法
- 01-10C#中split用法實例總結
- 01-10SublimeText編譯C開發(fā)環(huán)境設置
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 04-02jquery與jsp,用jquery
- 01-11ajax實現(xiàn)頁面的局部加載


