目录结构
1.题目
请你编写一个程序来计算两个日期之间隔了多少天。
日期以字符串形式给出,格式为 YYYY-MM-DD
,如示例所示。
示例:
输入:date1 = "2019-06-29", date2 = "2019-06-30"
输出:1
输入:date1 = "2020-01-15", date2 = "2019-12-31"
输出:15
提示:
- 给定的日期是
1971
年到2100
年之间的有效日期。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-days-between-two-dates
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
均以1971-01-01为基准算出天数做差即可。
public class Solution1360 {
@Test
public void test1360() {
// String date1 = "2019-06-29", date2 = "2019-06-30";
String date1 = "2020-01-15", date2 = "2019-12-31";
System.out.println(daysBetweenDates(date1, date2));
}
public int daysBetweenDates(String date1, String date2) {
return Math.abs(getDays(date1) - getDays(date2));
}
public int getDays(String date) {
int year = Integer.parseInt(date.split("-")[0]);
int month = Integer.parseInt(date.split("-")[1]);
int day = Integer.parseInt(date.split("-")[2]);
int[] days = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
int count = 0;
for (int i = 1971; i < year; i++) {
count += 365;
if ((i % 100 == 0 && i % 400 == 0) || (i % 100 != 0 && i % 4 == 0)) {
count++;
}
}
count += days[month - 1] + day;
if (month > 2) {
if ((year % 100 == 0 && year % 400 == 0) || (year % 100 != 0 && year % 4 == 0)) {
count++;
}
}
return count;
}
}
- 时间复杂度:
- 空间复杂度: