C/C++判断传入的UTC时间是否在今天

在项目中经常会显示一个时间,如果这个时间在今日内就显示为时分秒,否则显示为年月日。

这里先给出一个正确的版本:

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

}

在函数中struct tm *localtime(const time_t *);中返回的指针指向的是一个全局变量,如果把函数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声明成了指针。运行程序就会发现,这个函数返回的总是ture,为什么呢?
因为在 struct   tm * curDate =  localtime (&timeCur);中返回的指针指向的是一个全局变量,即curDate也指向这个全局变量。
struct   tm * argsDate =  localtime (&utc_time);中返回额指针也指向的这个全局变量,所以argsDate和cur指向的是同一个全局变量,他们的内存区域是同一块。
在第二次调用localtime()时,修改了全局变量的值,curDate也随之改变,因此curDate == argsDate;所以返回的结果衡等于true。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值