日付範囲の年数と日数を返すメソッドを作成しました。James K. Polkがコメントで述べたように、日を 365、365.2425、または 366 で割ると、1 年の小数部分を取得できます。
テスト結果はこちら。
From 01 Jan 1987 to 01 Jul 2013 is an interval of 26 years and 182 days.
From 01 Jul 2012 to 01 Jul 2013 is an interval of 1 years and 1 days.
From 01 Jul 2012 to 31 Jul 2012 is an interval of 0 years and 31 days.
From 01 Apr 2012 to 31 Dec 2012 is an interval of 0 years and 275 days.
そして、これがコードです。基本的には、開始日から終了日までの年月日を1日1日数えています。
このコードは、Java 6、Java 7 以降で動作します。
package com.ggl.testing;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateRangeCalculator {
private static final SimpleDateFormat format = new SimpleDateFormat(
"dd MMM yyyy");
public static void main(String[] args) {
DateRangeCalculator dateRangeCalculator = new DateRangeCalculator();
calculateDateInterval(dateRangeCalculator, "01 Jan 1987", "01 Jul 2013");
calculateDateInterval(dateRangeCalculator, "01 Jul 2012", "01 Jul 2013");
calculateDateInterval(dateRangeCalculator, "01 Jul 2012", "31 Jul 2012");
calculateDateInterval(dateRangeCalculator, "01 Apr 2012", "31 Dec 2012");
}
private static void calculateDateInterval(
DateRangeCalculator dateRangeCalculator, String startDateString,
String endDateString) {
try {
Date startDate = format.parse(startDateString);
Date endDate = format.parse(endDateString);
DateInterval dateInterval = dateRangeCalculator.getDateInterval(
startDate, endDate);
System.out.println("From " + format.format(startDate) + " to "
+ format.format(endDate) + " is an interval of "
+ dateInterval.getYears() + " years and "
+ dateInterval.getDays() + " days.");
} catch (ParseException e) {
e.printStackTrace();
}
}
public DateInterval getDateInterval(Date startDate, Date endDate) {
Calendar startCalendar = createCalendar(startDate);
Calendar endCalendar = createCalendar(endDate);
int years = -1;
while (!startCalendar.after(endCalendar)) {
startCalendar.add(Calendar.YEAR, 1);
years++;
}
startCalendar.add(Calendar.YEAR, -1);
int days = 0;
while (!startCalendar.after(endCalendar)) {
startCalendar.add(Calendar.DAY_OF_YEAR, 1);
days++;
}
return new DateInterval(years, days);
}
private Calendar createCalendar(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
public class DateInterval {
private final int years;
private final int days;
public DateInterval(int years, int days) {
this.years = years;
this.days = days;
}
public int getYears() {
return years;
}
public int getDays() {
return days;
}
}
}