亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C/C++判斷傳入的UTC時(shí)間是否當(dāng)天的實(shí)現(xiàn)方法

 更新時(shí)間:2014年01月09日 15:29:21   作者:  
在項(xiàng)目中經(jīng)常會(huì)顯示一個(gè)時(shí)間,如果這個(gè)時(shí)間在今日內(nèi)就顯示為時(shí)分秒,否則顯示為年月日,有需要的朋友可以參考一下

這里先給出一個(gè)正確的版本:

復(fù)制代碼 代碼如下:

#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 *);中返回的指針指向的是一個(gè)全局變量,如果把函數(shù)bool IsInToday(long utc_time);寫(xiě)成樣,會(huì)有什么問(wèn)題呢?

復(fù)制代碼 代碼如下:

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聲明成了指針。運(yùn)行程序就會(huì)發(fā)現(xiàn),這個(gè)函數(shù)返回的總是ture,為什么呢?
因?yàn)樵趕truct tm* curDate = localtime(&timeCur);中返回的指針指向的是一個(gè)全局變量,即curDate也指向這個(gè)全局變量。
在struct tm* argsDate = localtime(&utc_time);中返回額指針也指向的這個(gè)全局變量,所以argsDate和cur指向的是同一個(gè)全局變量,他們的內(nèi)存區(qū)域是同一塊。
在第二次調(diào)用localtime()時(shí),修改了全局變量的值,curDate也隨之改變,因此curDate == argsDate;所以返回的結(jié)果衡等于true。

相關(guān)文章

最新評(píng)論