我写了一个返回日期范围内的年数和天数的方法。正如James K. Polk在他的评论中提到的那样,您可以将天除以 365、365.2425 或 366 以获得一年的小数部分。
以下是测试结果。
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.
这是代码。基本上,我是从开始日期到结束日期,逐年计算。
此代码适用于 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;
}
}
}