查找两个日期之间的月数,包括额外的天数?

时间:2012-01-03 07:31:50

标签: java

我有一个要求,我需要找出两个日期之间的月数。我尝试了几个例子,但都排除了额外天数。请看下面的例子?

2010/03/22 -- fromdate
2010/05/30 -- todate

如果我们在这些日期之间找到差异,那么它将返回2个月。其中不包括8个额外的日期。我需要输出 2.8 2 months and 8 days)。我怎么能实现它?

谢谢!

4 个答案:

答案 0 :(得分:7)

您可以使用Joda Time

LocalDate date1 = new LocalDate(2010, 3, 22);
LocalDate date2 = new LocalDate(2010, 5, 30);
PeriodType monthDay = PeriodType.yearMonthDay().withoutYears();
Period difference = new Period(date1, date2, monthDay);
int months = difference.getMonths();
int days = difference.getDays();

答案 1 :(得分:0)

请考虑使用Joda time

答案 2 :(得分:0)

Change this method little to get that extra days.
/**
 * Gets number of months between two dates. 
 * <p>Months are calculated as following:</p>
 * <p>After calculating number of months from years and months from two dates,
 * if there are still any extra days, it will be considered as one more month.
 * For ex, Months between 2012-01-01 and 2013-02-06 will be 14 as 
 * Total Months = Months from year difference are 12 + Difference between months in dates is 1  
 * + one month since day 06 in enddate is greater than day 01 in startDate.
 * </p>
 * @param startDate
 * @param endDate
 * @return
 */
public static int getMonthsBetweenDates(Date startDate, Date endDate)
{
    if(startDate.getTime() > endDate.getTime())
    {
        Date temp = startDate;
        startDate = endDate;
        endDate = temp;
    }
    Calendar startCalendar = Calendar.getInstance(); 
    startCalendar.setTime(startDate);
    Calendar endCalendar = Calendar.getInstance();
    endCalendar.setTime(endDate);

    int yearDiff = endCalendar.get(Calendar.YEAR)- startCalendar.get(Calendar.YEAR);
    int monthsBetween = endCalendar.get(Calendar.MONTH)-startCalendar.get(Calendar.MONTH) +12*yearDiff;

    if(endCalendar.get(Calendar.DAY_OF_MONTH) >= startCalendar.get(Calendar.DAY_OF_MONTH))
        monthsBetween = monthsBetween + 1;
    return monthsBetween;

}

答案 3 :(得分:-1)

使用

 org.joda.time.Month#monthsBetween(start, end)