Java Date Difference diffMonth(Date before, Date after)

Here you can find the source of diffMonth(Date before, Date after)

Description

diff Month

License

Open Source License

Declaration

public static int diffMonth(Date before, Date after) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

public class Main {

    public static int diffMonth(Date before, Date after) {
        int monthAll = 0;
        int yearsX = diffYear(before, after);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(before);//from  ww w. j  av  a  2  s. c o m
        c2.setTime(after);
        int monthsX = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
        monthAll = yearsX * 12 + monthsX;
        int daysX = c2.get(Calendar.DATE) - c1.get(Calendar.DATE);
        if (daysX > 0) {
            monthAll = monthAll + 1;
        }
        return monthAll;
    }

    public static int diffYear(Date before, Date after) {
        return getYear(after) - getYear(before);
    }

    public static int getYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }
}

Related

  1. differenceMonth(Date date1, Date date2)
  2. differenceOnMonth(Date date1, Date date2)
  3. differenceOnYear(Date date1, Date date2)
  4. diffIntoMilliSecond(java.util.Date date, java.util.Date date1)
  5. diffMillis(Date d1, Date d2)
  6. diffMonth(Date start, Date end)
  7. diffOfDate(String begin, String end)
  8. diffY(Date endDate, Date startDate)
  9. getDateDiff(String startDate, String endDate)