题目:
请你编写一个程序来计算两个日期之间隔了多少天。
日期以字符串形式给出,格式为 YYYY-MM-DD
,如示例所示。
解法一(暴力转化):
我们可以将两个日期转化为距离 0年 1 月 1 日的天数。这一转化过程可以直接暴力求解:从0年 1 月 1 日日期开始,先计算出月和年对应的天数,再把之前年数加起来算综合,最后相减取绝对值得到两个日期之间间隔的天数,如下为笔者代码:
class Solution {
public:
//day_number用于计算两个日期的月和日日期的总和天数
int day_number(int year11, int mounth11, int day11){
int result11=0;
bool a;
if(year11%4==0 and year11%100!=0){
a=false;
}
else if(year11%4==0 and year11%100==0 and year11%400==0){
a=false;
}
else{
a=true;
}
if(a){
for(int i=1;i<mounth11;i++){
switch(i){
case 2:
result11+=28;
continue;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
result11+=31;
continue;
default:
result11+=30;
}
}
}
else{
for(int i=1;i<mounth11;i++){
switch(i){
case 2:
result11+=29;
continue;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
result11+=31;
continue;
default:
result11+=30;
}
}
}
result11+=day11;
return result11;
}
int daysBetweenDates(string date1, string date2) {
int result1=0;
int result2=0;
int result=0;
int year1=std::stoi(date1.substr(0,4));
int year2=std::stoi(date2.substr(0,4));
int mounth1=std::stoi(date1.substr(5,7));
int mounth2=std::stoi(date2.substr(5,7));
int day1=std::stoi(date1.substr(8,10));
int day2=std::stoi(date2.substr(8,10));
result1 = day_number(year1,mounth1,day1);
result2 = day_number(year2,mounth2,day2);
//for循环用于计算date1年从0年到date1年的总天数
for(int i=0;i<year2;i++){
if(i%4==0 and i%100!=0){
result2+=366;
}
else if(i%4==0 and i%100==0 and i%400==0){
result2+=366;
}
else{
result2+=365;
}
}
//for循环用于计算date2年从0年到date2年的总天数
for(int i=0;i<year1;i++){
if(i%4==0 and i%100!=0){
result1+=366;
}
else if(i%4==0 and i%100==0 and i%400==0){
result1+=366;
}
else{
result1+=365;
}
}
//取绝对值得到result最后两个日期之间的天数结果
result=abs(result2-result1);
return result;
}
};
笔者小记:需要注意的是下面两点可能会产生的问题
1、闰年的定义(366天,2月份天数为29天):可以被4整除,但是不能被100整除,如果既能被4整除也能被100整除,必须还得被400整除才能是闰年,否则均为平年(365天),2月份天数为28天。
2、switch(){case1: case2:}函数,满足从第一个满足case的进入,然后一直执行到switch(){}尾部,因此如后面代码有针对参数变量的修改影响结果时,需要及时break或者continue跳出或直接执行下一次循环,在代码设计的时候需要关注。