Here you can find the source of getMonthsDifference(Date earlierDate, Date laterDate)
Parameter | Description |
---|---|
earlierDate | The earlier date, chronologically |
laterDate | The later date, chronologically |
public static int getMonthsDifference(Date earlierDate, Date laterDate)
//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; } }