Sunday, August 15, 2021

3 ways to get number of months and year between two dates in Java? Examples

Earlier I have talked about how to calculate the number of days between two dates in Java (see here), and now you will learn how to get the number of months and years between dates. Though it may look easy, it's not that easy to calculate months and years between dates, unless you take care of all kinds of nuisances like Daylight saving time and when daylight change occurs, leap seconds, and an extra day added in a leap year. Unfortunately, JDK doesn't have a standard method like the Period.between() methods of Java 8 before solving this problem.

So, if you have to calculate the number of months and years between given dates, you have three main options, first, use Calendar class to write your method to find a number of months and years between given dates, second, use Joda-time library and the third option is to upgrade to Java 8.

The third option is best if you are doing a new development but often it's not an option for existing projects, for them option 2 is their best bet. Just add the Joda-Time library in your build path, sit back and relax and let joda do all the heavy lifting for you.

The first option may look attractive to the purist who doesn't like the presence of an open-source library and solely relies on JDK, but it's difficult to get it right and will require huge testing effort to sign off.

In this article, I'll show you all three ways to find the number of months and years between two dates in Java. You can compare by yourself how much effort is required in each of these options and what are the pros and cons of each option.

Btw, if you are not familiar with the new Date and Time API added on Java 8 then I suggest you first go through a comprehensive and up-to-date Java course like The Complete Java MasterClass on Udemy. It's also very affordable and you can buy in just $10 on Udemy sales which happen every now and then.




How to get the number of months and years between given dates

Here are my three ways to calculate the number of months and years between two given dates in Java. The first approach uses Calendar and it will work in JDK 1.4, JDK 1.5, JDK 1.6, JDK 1.7, and JDK 1.8 because Calendar was first added on JDK 4.  

The second approach uses the Joda-Time library, which requires Java 5, so it will also work on any Java version above JDK 1.5. It also has no other dependencies. The third approach requires you to upgrade to JDK 8.


1. Using Calendar:

Here is the complete code to find the number of months and years between two dates in Java using java.util.Calendar class. It uses GregorianCalendar, which we all use in our day-to-day life. You must remember that month in the Calendar starts from zero i.e. the first month, January is equal to zero.

 // Using Calendar - calculating number of months between two dates  
        Calendar birthDay = new GregorianCalendar(1955, Calendar.MAY, 19);
        Calendar today = new GregorianCalendar();
        today.setTime(new Date());
        
        int yearsInBetween = today.get(Calendar.YEAR) 
                                - birthDay.get(Calendar.YEAR);
        int monthsDiff = today.get(Calendar.MONTH) 
                                - birthDay.get(Calendar.MONTH);
        long ageInMonths = yearsInBetween*12 + monthsDiff;
        long age = yearsInBetween;
        
        System.out.println("Number of months since James gosling born : "
                + ageInMonths);
        
        System.out.println("Sir James Gosling's age : " + age);

Pros :
1) No need for any third-party library.

Cons :
1) Difficult to use, not intuitive

If you want to learn more about Calendar class and how to use it in the correct way, please see Core Java Volume 1- Fundamentals 11 Edition by Cay S. Horstmann.



2. Using Joda-Time:

Here is our second solution to this problem using the Joda-Time library. This time, we are using the LocalDate class, similar to LocalDate of JDK 8, which also represents just date without any time component. 

Once you have the LocalDate, you can use Months.monthsBetween() and Years.yearsBetween() method to calcualte the number of months and years between two dates in Java.

LocalDate jamesBirthDay = new LocalDate(1955, 5, 19);
LocalDate now = new LocalDate(2015, 7, 30);
        
int monthsBetween = Months.monthsBetween(jamesBirthDay, now).getMonths();
int yearsBetween = Years.yearsBetween(jamesBirthDay, now).getYears();
        
System.out.println("Month since father of Java born : " 
                    + monthsBetween);
System.out.println("Number of years since father of Java born : " 
                    + yearsBetween);


Pros :
1) Robust and accurate.
2) handles leap year and daylight saving time.
3) Easy to use

Cons :
1) Adds a third-party library dependency to your project.


3 ways to get number of months and year between two dates in Java?



3. Using Java 8 :

This is the third way to get the number of months and years between two dates in Java. This is also the simplest and standard way to solve this problem if you are using Java SE 8.

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;

/**
 * Java Program to calculate number of years and months
 */
public class Java8Demo {

    @SuppressWarnings("empty-statement")
    public static void main(String[] args) {
        LocalDate bday = LocalDate.of(1955, Month.MAY, 19);
        LocalDate today = LocalDate.now();
        
        Period age = Period.between(bday, today);
        int years = age.getYears();
        int months = age.getMonths();
        
        System.out.println("number of years: " + years);
        System.out.println("number of months: " + months);
    }

}

Output
number of years: 61
number of months: 4

Pros :
1) no external library dependency
2) handles leap year and daylight saving time

Cons :
1) You cannot use it if you are not running on Java 8

If you want to learn more about the new Date and Time API of Java 8, please read Java SE 8 for Really Impatient By Cay S. Horstmann. One of the best books to learn new features on Java SE 8 in a quick time.

How to find number of months and year between two dates in Java 8?


How to find the number of months or years between dates in Java 8

Here is our sample program to find the number of years and months between two given dates using all three ways. The code is the same as given in the example above, I have just combined them so that you can run it in your Eclipse or NetBeans IDE.

import java.time.Month;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.joda.time.LocalDate;
import org.joda.time.Months;
import org.joda.time.Years;

/**
 * Java Program to calculate number of months between two dates
 * You will learn three ways to do this across Java version.
 * 
 * @author WINDOWS 8
 */
public class Java8Demo {
    
    public static void main(String args[]) {
      
        // Using Calendar - calculating number of months between two dates  
        Calendar birthDay = new GregorianCalendar(1955, Calendar.MAY, 19);
        Calendar today = new GregorianCalendar();
        today.setTime(new Date());
        
        int yearsInBetween = today.get(Calendar.YEAR) 
                                 - birthDay.get(Calendar.YEAR);
        int monthsDiff = today.get(Calendar.MONTH) 
                                 - birthDay.get(Calendar.MONTH);
        long ageInMonths = yearsInBetween*12 + monthsDiff;
        long age = yearsInBetween;
        
        System.out.println("Number of months since James gosling born : "
                + ageInMonths);
        
        System.out.println("Sir James Gosling's age : " + age);
        
        
        // Using Joda - number of months between dates
        LocalDate jamesBirthDay = new LocalDate(1955, 5, 19);
        LocalDate now = new LocalDate(2015, 7, 30);
        
        int monthsBetween = Months.monthsBetween(jamesBirthDay, now)
                                  .getMonths();
        int yearsBetween = Years.yearsBetween(jamesBirthDay, now)
                                  .getYears();
        
        System.out.println("Month since father of Java born : " 
                              + monthsBetween);
        System.out.println("Number of years since father of Java born : " 
                              + yearsBetween);
        
        
        // Using Java 8 - get number of months between two dates
        java.time.LocalDate bday = java.time.LocalDate.of(1955, Month.MAY, 19);
        
        
    }
}


That's all about how to calculate the number of months between two dates in Java. If you are still running in Java 6 or Java 7, then you can use the Calendar class or take help from the joda-time library. If you have the option to upgrade to Java 8, then nothing comes closer to Java 8's date and time API for these kinds of basic date time arithmetic.

 You can calculate the difference between dates to find the number of days, months, and years using Java 8 API in a couple of lines. Since the library is already tested, you don't need to spend time on that, you are totally free to focus on your business logic. You can further join these Java 8 courses to learn more about the new date and time API of Java 8.


Other Date and Time tutorials for Java Programmers
  • 20 examples of new Date and Time API in Java 8  (tutorial)
  • How to calculate the difference between two dates in Java? (solution)
  • How to convert String to LocalDateTime in Java 8? (tutorial)
  • How to add and subtract days, months, years, and hours from date and time in Java? (answer)
  • Difference between java.sql.Time, Timestamp, and java.util.Date in Java? (answer)
  • How to get the current date, month, year, and day of the week in Java? (tutorial)
  • How to convert java.util.Date to java.sql.Date in JDBC? (tutorial)
  • Difference between java.sql.Date and java.util.Date in JDBC? (answer)
  • How to parse String to LocalDate in Java 8 using DateTimeFormatter? (tutorial)

Thanks for reading this article so far. If you like this Java Date tutorial then please share it with your friends and colleagues. 

6 comments :

Anonymous said...

not proper solution.

Anonymous said...

following code giving wrong output.
Calendar today = Calendar.getInstance();
System.out.println("Current Month "+today.get(Calendar.MONTH));

Calendar nextMont = Calendar.getInstance();
nextMont.add(Calendar.MONTH, 1);
System.out.println("Current Month "+nextMont.get(Calendar.MONTH));

int monthsDiff = today.get(Calendar.MONTH)
- nextMont.get(Calendar.MONTH);
System.out.println("months Diff "+monthsDiff);

javin paul said...

Hello @Unknown, month starts from zero in Calendar, better you use Java 8 Date Time API, if you can but if you had to use Calendar take note of that.

mudassarnagori said...

The option 3 using JDK8 in which output for your programme is wrong for the number of months.Please correct it.
Output
number of years: 61
number of months: 4

javin paul said...

Yes, some typos, thanks for point it out.

javin paul said...

Actually, I think there is more than typo, I will take a closer look.

Post a Comment