[英]how to find the total number of months between the two dates including extra days?
[英]Finding number of months between two dates including extra days?
我有一个要求,我需要找出两个日期之间的月份数。 我尝试了几个例子,但都排除了多余的日子。 请看下面的例子吗?
2010/03/22 -- fromdate
2010/05/30 -- todate
如果我们发现这些日期之间的差异,则返回2个月。此处不包括8天的额外时间。 我需要把2.8 ( 2 months and 8 days
)放出来。 我该如何实现?
谢谢!
您可以为此使用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();
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;
}
考虑为此使用Joda时间 。
采用
org.joda.time.Month#monthsBetween(start, end)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.