Here you can find the source of monthsBetween(String from, String to, String format)
public static int monthsBetween(String from, String to, String format) throws IOException
//package com.java2s; /**//from w w w . ja va 2 s . com * Copyright 2014 tgrape Inc. * * 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.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class Main { public static int monthsBetween(String from, String to, String format) throws IOException { SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.UK); Calendar calendar = Calendar.getInstance(Locale.UK); calendar.setFirstDayOfWeek(Calendar.MONDAY); calendar.setMinimalDaysInFirstWeek(4); Date fromDate = null; Date toDate = null; try { fromDate = formatter.parse(from); toDate = formatter.parse(to); } catch (ParseException e) { throw new IOException(e.getMessage()); } if (fromDate.compareTo(toDate) == 0) return 0; SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy", Locale.UK); SimpleDateFormat monthFormat = new SimpleDateFormat("MM", Locale.UK); SimpleDateFormat dayFormat = new SimpleDateFormat("dd", Locale.UK); int fromYear = Integer.parseInt(yearFormat.format(fromDate)); int toYear = Integer.parseInt(yearFormat.format(toDate)); int fromMonth = Integer.parseInt(monthFormat.format(fromDate)); int toMonth = Integer.parseInt(monthFormat.format(toDate)); int fromDay = Integer.parseInt(dayFormat.format(fromDate)); int toDay = Integer.parseInt(dayFormat.format(toDate)); int result = 0; result += ((toYear - fromYear) * 12); result += (toMonth - fromMonth); // ceil & floor if (((toDay - fromDay) > 0)) result += toDate.compareTo(fromDate); return result; } }