回答編集履歴
1
コード追加
answer
CHANGED
@@ -1,5 +1,6 @@
|
|
1
1
|
日付差分だけならdifferenceDaysの中身がこんな感じでいかが?
|
2
2
|
|
3
|
+
```java
|
3
4
|
Calendar cal1 = Calendar.getInstance();
|
4
5
|
cal1.setTime(date1);
|
5
6
|
Calendar cal2 = Calendar.getInstance();
|
@@ -12,4 +13,53 @@
|
|
12
13
|
}
|
13
14
|
cal1.setTimeInMillis(longtime1);
|
14
15
|
cal1.add(Calendar.DATE, -1 * cal2.get(Calendar.DATE);
|
15
|
-
return (int)cal1.get(Calendar.DATE);
|
16
|
+
return (int)cal1.get(Calendar.DATE);
|
17
|
+
```
|
18
|
+
|
19
|
+
【追記】
|
20
|
+
年月日時分秒で差を求めるのだと下記のような感じになるかな?
|
21
|
+
|
22
|
+
```java
|
23
|
+
Calendar c1 = Calendar.getInstance();
|
24
|
+
c1.setTime(date1);
|
25
|
+
|
26
|
+
Calendar c2 = Calendar.getInstance();
|
27
|
+
c2.setTime(date2);
|
28
|
+
|
29
|
+
// millisecond
|
30
|
+
c1.set(Calendar.MILLISECOND, 0);
|
31
|
+
c2.set(Calendar.MILLISECOND, 0);
|
32
|
+
|
33
|
+
// second
|
34
|
+
int sec = c1.get(Calendar.SECOND) - c2.get(Calendar.SECOND);
|
35
|
+
sec += (sec < 0) ? 60 : 0;
|
36
|
+
c1.add(Calendar.SECOND, -1 * sec);
|
37
|
+
|
38
|
+
// minute
|
39
|
+
int min = c1.get(Calendar.MINUTE) - c2.get(Calendar.MINUTE);
|
40
|
+
min += (min < 0) ? 60 : 0;
|
41
|
+
c1.add(Calendar.MINUTE, -1 * min);
|
42
|
+
|
43
|
+
// hour
|
44
|
+
int hour = c1.get(Calendar.HOUR) - c2.get(Calendar.HOUR);
|
45
|
+
hour += (hour < 0) ? 24 : 0;
|
46
|
+
c1.add(Calendar.HOUR, -1 * hour);
|
47
|
+
|
48
|
+
// day
|
49
|
+
long longtime1 = c1.getTimeInMillis();
|
50
|
+
c1.set(Calendar.DATE, 1);
|
51
|
+
c1.add(Calendar.DATE, -1);
|
52
|
+
int dayInLastMonth = c1.get(Calendar.DATE);
|
53
|
+
c1.setTimeInMillis(longtime1);
|
54
|
+
int day = c1.get(Calendar.DATE) - c2.get(Calendar.DATE);
|
55
|
+
day += (day < 0) ? dayInLastMonth : 0;
|
56
|
+
c1.add(Calendar.DATE, -1 * day);
|
57
|
+
|
58
|
+
// month
|
59
|
+
int month = c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
|
60
|
+
month += (month < 0) ? 12 : 0;
|
61
|
+
c1.add(Calendar.MONTH, -1 * month);
|
62
|
+
|
63
|
+
// year
|
64
|
+
int year = c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
|
65
|
+
```
|