有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

如果我们发现这些日期之间存在差异,则返回2个月。这里不包括额外的8天。我需要输出为2.8(^{)。我怎样才能做到呢

谢谢


共 (4) 个答案

  1. # 1 楼答案

    您可以使用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();
    
  2. # 2 楼答案

    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. # 3 楼答案

    考虑使用此{a1}。

  4. # 4 楼答案

    使用

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