Number of Days Between Two Dates LeetCode solution in Java

1
class Solution {
2
public int daysBetweenDates(String date1, String date2) {
3
String[] d1 = date1.split("-");
4
String[] d2 = date2.split("-");
5
return (int)
6
Math.abs(
7
daysFrom1971(Integer.parseInt(d1[0]), Integer.parseInt(d1[1]), Integer.parseInt(d1[2]))
8
- daysFrom1971(
9
Integer.parseInt(d2[0]), Integer.parseInt(d2[1]), Integer.parseInt(d2[2])));
10
}
11

12
private int daysFrom1971(int year, int month, int day) {
13
int total = 0;
14
// count years first
15
total += (year - 1971) * 365;
16
for (int i = 1972; i < year; i += 4) {
17
if (isLeapYear(i)) total++;
18
}
19
int feb = isLeapYear(year) ? 29 : 28;
20
// sum months and days
21
switch (month) {
22
case 12:
23
total += 30; // 11
24
case 11:
25
total += 31; // 10
26
case 10:
27
total += 30; // 9
28
case 9:
29
total += 31; // 8
30
case 8:
31
total += 31; // 7
32
case 7:
33
total += 30; // 6
34
case 6:
35
total += 31; // 5
36
case 5:
37
total += 30; // 4
38
case 4:
39
total += 31; // 3
40
case 3:
41
total += feb; // 2
42
case 2:
43
total += 31;
44
case 1:
45
total += day;
46
}
47
return total;
48
}
49

50
private boolean isLeapYear(int i) {
51
return (i % 4 == 0) && ((i % 100 == 0 && i % 400 == 0) || i % 100 != 0);
52
}
53
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0