回答編集履歴

1 コード追加

tkturbo

tkturbo score 5166

2016/02/25 16:28  投稿

日付差分だけならdifferenceDaysの中身がこんな感じでいかが?
```java  
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
long longtime1 = c2.getTimeInMillis();
while(cal1.after(cal2)){
   longtime1 = cal1.getTimeInMillis();
   cal1.add(Calendar.MONTH, -1);
}
cal1.setTimeInMillis(longtime1);
cal1.add(Calendar.DATE, -1 * cal2.get(Calendar.DATE);
return (int)cal1.get(Calendar.DATE);
return (int)cal1.get(Calendar.DATE);
```
【追記】
年月日時分秒で差を求めるのだと下記のような感じになるかな?
```java
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
Calendar c2 = Calendar.getInstance();
c2.setTime(date2);
// millisecond
c1.set(Calendar.MILLISECOND, 0);
c2.set(Calendar.MILLISECOND, 0);
// second
int sec = c1.get(Calendar.SECOND) - c2.get(Calendar.SECOND);
sec += (sec < 0) ? 60 : 0;
c1.add(Calendar.SECOND, -1 * sec);
// minute
int min = c1.get(Calendar.MINUTE) - c2.get(Calendar.MINUTE);
min += (min < 0) ? 60 : 0;
c1.add(Calendar.MINUTE, -1 * min);
// hour
int hour = c1.get(Calendar.HOUR) - c2.get(Calendar.HOUR);
hour += (hour < 0) ? 24 : 0;
c1.add(Calendar.HOUR, -1 * hour);
// day
long longtime1 = c1.getTimeInMillis();
c1.set(Calendar.DATE, 1);
c1.add(Calendar.DATE, -1);
int dayInLastMonth = c1.get(Calendar.DATE);
c1.setTimeInMillis(longtime1);
int day = c1.get(Calendar.DATE) - c2.get(Calendar.DATE);
day += (day < 0) ? dayInLastMonth : 0;
c1.add(Calendar.DATE, -1 * day);
// month
int month = c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
month += (month < 0) ? 12 : 0;
c1.add(Calendar.MONTH, -1 * month);
// year
int year = c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
```

思考するエンジニアのためのQ&Aサイト「teratail」について詳しく知る