user1016403
user1016403

Reputation: 12621

Finding number of months between two dates including extra days?

i have a requirement where i need to find out number of months between two dates. i tried few examples but all are excluding number of extra days. please see in below example?

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

if we find diff between those dates then it is returning 2 months.here it is excluding 8 extra days. i need out put as 2.8(2 months and 8 days). how can i achieve it?

Thanks!

Upvotes: 1

Views: 5388

Answers (4)

pavanlapr
pavanlapr

Reputation: 279

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;

}

Upvotes: 0

Peter
Peter

Reputation: 1

use

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

Upvotes: -1

Jon Skeet
Jon Skeet

Reputation: 1499770

You can use Joda Time for this:

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();

Upvotes: 7

Francis Upton IV
Francis Upton IV

Reputation: 19443

Consider using Joda time for this.

Upvotes: 0

Related Questions