国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

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

2020-01-26 15:38:26
字體:
供稿:網(wǎng)友

這里先給出一個正確的版本:

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

復(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聲明成了指針。運行程序就會發(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。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 册亨县| 海晏县| 景泰县| 南靖县| 南雄市| 舞钢市| 佛教| 那坡县| 长白| 遂平县| 莱西市| 江安县| 大邑县| 漳浦县| 石景山区| 绍兴市| 茂名市| 清水河县| 云南省| 高唐县| 疏勒县| 本溪市| 迁安市| 阿拉善右旗| 海城市| 长子县| 故城县| 隆尧县| 福海县| 黎城县| 凯里市| 牙克石市| 商水县| 淮南市| 郓城县| 洞口县| 南江县| 通渭县| 灵台县| 绥中县| 嘉义市|