Here you can find the source of getMonthSpan(Date start, Date end)
Parameter | Description |
---|---|
start | The start date. |
end | The end date. |
public static int getMonthSpan(Date start, Date end)
//package com.java2s; //License from project: Apache License import static java.util.Calendar.DAY_OF_MONTH; import static java.util.Calendar.HOUR_OF_DAY; import static java.util.Calendar.MILLISECOND; import static java.util.Calendar.MINUTE; import static java.util.Calendar.MONTH; import static java.util.Calendar.SECOND; import static java.util.Calendar.YEAR; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main { /**/* w w w .ja v a 2 s .c om*/ * This method returns the number of months between the specified dates. * * @param start The start date. * @param end The end date. * * @return The number of months between the specified dates. */ public static int getMonthSpan(Date start, Date end) { GregorianCalendar first = createCalendar(start); GregorianCalendar last = createCalendar(end); int monthSpan = 0; first.set(DAY_OF_MONTH, 1); monthSpan += (last.get(MONTH) - first.get(MONTH)); monthSpan += 12 * (last.get(YEAR) - first.get(YEAR)); if (monthSpan < 0) { monthSpan = 0; } return monthSpan; } /** * This method creates and returns a new calendar. * * @return A new calendar. */ public static GregorianCalendar createCalendar() { return createCalendar(null); } /** * This method creates and returns a new calendar. * * @param date The date to initialize the calendar to. * * @return A new calendar. */ public static GregorianCalendar createCalendar(Date date) { GregorianCalendar calendar = new GregorianCalendar(); if (date == null) { date = new Date(); } calendar.setTime(date); clearClockFor(calendar); return calendar; } /** * This method sets the clock to 00:00:00:000. * * @param calendar The calendar to clear the clock for. */ public static void clearClockFor(Calendar calendar) { // Set time to 00:00:00:000 calendar.set(HOUR_OF_DAY, 0); calendar.set(MILLISECOND, 0); calendar.set(MINUTE, 0); calendar.set(SECOND, 0); } }