1. 问题描述:
请你编写一个程序来计算两个日期之间隔了多少天。
日期以字符串形式给出,格式为 YYYY-MM-DD,如示例所示。
示例 1:
输入:date1 = "2019-06-29", date2 = "2019-06-30"
输出:1
示例 2:
输入:date1 = "2020-01-15", date2 = "2019-12-31"
输出:15
提示:
给定的日期是 1971 年到 2100 年之间的有效日期。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-days-between-two-dates
2. 思路分析:
① 题目其实很好理解,关键是怎么样去处理这个细节的问题,首先是保证字符串date小于date2,假如大于的话交换一下字符串的顺序即可,对得到的date1余date2字符串使用split方法进行分割,得到对应的年月日,一个很简单的想法是先假设从date1的月份的1号开始,然后在循环中累计到达当前年份与月份需要经历的天数,所以循环的条件是当年分与月分都不相同,这个时候就可以对月份对应的天数进行累加
② 因为看成是1号开始,所以我们需要减去date1中的天数,因为这个是多算的天数,然后需要加上date2中的天数,因为循环中计算的是date1中的1号到date2中的1号所以需要加上date2的天数,其实这个也是比较好理解的
③ 需要注意一个坑是我们在循环中需要计算当前年份是否是闰年来进行对应2月份天数的更新
3. 代码如下:
class Solution {
/*中的月份计算出来累加天数*/
public int daysBetweenDates(String date1, String date2) {
/*确保第一个字符串小于第二个字符串*/
if (date1.compareTo(date2) > 0){
String t = date2;
date2 = date1;
date1 = t;
}
int []days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String curdate1[] = date1.split("-");
String curdate2[] = date2.split("-");
int year1 = Integer.parseInt(curdate1[0]);
int year2 = Integer.parseInt(curdate2[0]);
int month1 = Integer.parseInt(curdate1[1]);
int month2 = Integer.parseInt(curdate2[1]);
int day1 = Integer.parseInt(curdate1[2]);
int day2 = Integer.parseInt(curdate2[2]);
int res = 0;
while (year1 != year2 || month1 != month2){
/*判断出当前的年份是否是闰年*/
if ((year1 % 4 == 0 && year1 % 100 != 0) || year1 % 400 == 0) {
days[2] = 29;
}else days[2] = 28;
res += days[month1];
if (++month1 > 12) {
/*更新年份*/
++year1;
month1 = 1;
}
}
res = res - day1 + day2;
return res;
}
}