C/C++语言实现给定日期计算该日期与当前日期的相差天数

#include <stdio.h>
#include <time.h>
#include<math.h>
#define TRUE 1
#define FALSE 0

size_t StringToDatetime(char *str)
{
    time_t ocurtime;
    char buffer[80];
    struct tm tm_;
    int year, month, day;
    sscanf(str,"%d-%d-%d", &year, &month, &day);
    tm_.tm_year  = year-1900;//occur time 
    tm_.tm_mon   = month-1;
    tm_.tm_mday  = day;
    tm_.tm_hour = 0;
    tm_.tm_min = 0;
    tm_.tm_sec = 0;
    tm_.tm_isdst = 0;
    time_t curtime;//current time
    curtime = time(NULL);
    ocurtime=mktime(&tm_);
     if( ocurtime == -1 )
   {
       printf("错误:不能使用 mktime 转换时间。\n");
       return FALSE;
   }
   else
   {
    return floor(difftime(curtime,ocurtime)/(3600*24)); //秒时间
   }
}

int main(){
    char str[]="2020-9-08"
/*当前时间字串,理论上可以提供更多参数,参数格式需参照sscanf内格式化输入的传参格式,但小时,分钟和秒对天数之差没有影响;
*/
    time_t Diff=StringToDatetime(str);
    printf("the gap day frorm %s to current day is :%ld",str,Diff);

    return 0;
}

运行之后:

2020-9-08距离今天2020/9/29相差21天,结论正确。

参考材料:https://blog.csdn.net/charliye/article/details/50720812

               https://www.runoob.com/w3cnote/c-time-func-summary.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值