In this tutorial, you will see how to calculate the number of months in between two dates.
Calculate number of month in between two date.
In this example, you will see how to calculate the number of month in between two dates.
Here, we are using GregorianCalender() constructor for creating instance of Calendar class. After this we are using a set(int year, int month, int date) method of Calendar of java. It is used for setting values of fields year, month, date. Again repeats this process for another date. There is also a while loop, that is used for calculating total number of month between these date.
Code:import java.util.Calendar; import java.util.GregorianCalendar; public class NumberOfMonth { public static void main(String[] arr) { Calendar firstDate = new GregorianCalendar(); firstDate.set(2009, 07, 11); System.out.println("First Date : " + firstDate.get(Calendar.YEAR) + "/" + firstDate.get(Calendar.MONTH) + "/" + firstDate.get(Calendar.DATE)); Calendar secondDate = new GregorianCalendar(); secondDate.set(2010, 2, 11); System.out.println("Second Date : " + secondDate.get(Calendar.YEAR) + "/" + secondDate.get(Calendar.MONTH) + "/" + secondDate.get(Calendar.DATE)); int totalNumberOfMonth = 0; while (firstDate.before(secondDate)) { firstDate.add(Calendar.MONTH, 1); totalNumberOfMonth++; } System.out.println("Number of month in between two date : " + totalNumberOfMonth); } }Output
First Date : 2009/7/11
Second Date : 2010/2/11 Number of month in between two date : 7 |
[ 0 ] Comments