[leetcode]5169. 日期之间隔几天

在这里插入图片描述

不调库

class Solution {
public:
    int daysBetweenDates(string date1, string date2) {
        int year1 = stoi(date1.substr(0,4));
        int month1 = stoi(date1.substr(5,2));
        int day1 = stoi(date1.substr(8,2));
        int year2 = stoi(date2.substr(0,4));
        int month2 = stoi(date2.substr(5,2));
        int day2 = stoi(date2.substr(8,2));
        
        int days[2][13]= {{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31}};
        int res = 0;
        if(year1 > year2 || (year1 == year2 && month1 > month2) || (year1 == year2 && month1 == month2 && day1 > day2))
        {
            swap(year1,year2);
            swap(month1,month2);
            swap(day1,day2);
        }
        for(int i = year1; i < year2; i++)
        {
            if((i%4 == 0 && i % 100 != 0 ) || (i % 400 == 0))
            {
                res += 366;
            }
            else
            {
                res += 365;
            }
        }
        
        bool flag = (year2%4 == 0 && year2 % 100 != 0 ) || (year2 % 400 == 0);
        for(int i = 1; i < month2; i++)
        {
            res += days[flag][i];
        }
        //cout<<res<<endl;
        res += day2;
        //cout<<res<<" "<<day2<<endl;
        flag = (year1%4 == 0 && year1 % 100 != 0 ) || (year1 % 400 == 0);
        for(int i = 1; i < month1; i++)
        {
            res -= days[flag][i];
        }
        //cout<<res;
        res -= day1;
        return res;
    }
};

调库:

class Solution {
public:
    int daysBetweenDates(string date1, string date2) {
        int year1 = stoi(date1.substr(0,4));
        int month1 = stoi(date1.substr(5,2));
        int day1 = stoi(date1.substr(8,2));
        int year2 = stoi(date2.substr(0,4));
        int month2 = stoi(date2.substr(5,2));
        int day2 = stoi(date2.substr(8,2));
        

        
        struct tm a = {0};
        struct tm b = {0};
        
        a.tm_year = year1 - 1900; //tm_year等于实际年份-1900
        a.tm_mon = month1 - 1;//tm_mon:0 1 2 3 4 5 6 7 8 9 10 11 从0开始
        a.tm_mday = day1;
        b.tm_year = year2 - 1900;
        b.tm_mon = month2 - 1;        
        b.tm_mday = day2;
        
        double second = difftime(mktime(&b),mktime(&a));
        
        return abs(second)/(24*60*60);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值