Java Day Between getMonthsDifference(Date earlierDate, Date laterDate)

Here you can find the source of getMonthsDifference(Date earlierDate, Date laterDate)

Description

Gets the number of months separating the two dates.

License

Apache License

Parameter

Parameter Description
earlierDate The earlier date, chronologically
laterDate The later date, chronologically

Return

the number of months separating the two dates.

Declaration

public static int getMonthsDifference(Date earlierDate, Date laterDate) 

Method Source Code

//package com.java2s;
/*/*from  ww w .ja  v  a 2s .  c o  m*/
 * Copyright (C) 2009 JavaRosa
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import java.util.Calendar;
import java.util.Date;

public class Main {
    /**
     * Gets the number of months separating the two dates.
     * @param earlierDate The earlier date, chronologically
     * @param laterDate The later date, chronologically
     * @return the number of months separating the two dates.
     */
    public static int getMonthsDifference(Date earlierDate, Date laterDate) {
        Date span = new Date(laterDate.getTime() - earlierDate.getTime());
        Date firstDate = new Date(0);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(firstDate);
        int firstYear = calendar.get(Calendar.YEAR);
        int firstMonth = calendar.get(Calendar.MONTH);

        calendar.setTime(span);
        int spanYear = calendar.get(Calendar.YEAR);
        int spanMonth = calendar.get(Calendar.MONTH);
        int months = (spanYear - firstYear) * 12 + (spanMonth - firstMonth);
        return months;
    }
}

Related

  1. getDiffMilliSeconds(Date form, Date to)
  2. getManyWeeksDifference(Date a, Date b)
  3. getMinuteDiffByTime(Date time1, Date time2)
  4. getMinutesDifference(final Date begin, final Date end)
  5. getMonthDifference(Date from, Date to)
  6. getNumDaysDiffExclTime(Date date1, Date date2)
  7. getTimeDifference(Date d1, Date d2)
  8. getTimeDifference(Date date1, Date date2)
  9. getTimeDifference(Date otherDate)