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

Earlier I have talked about how to calculate a 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 Period.between() method of Java 8 before to solve 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 year 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 project, for them option 2 is their best bet. Just add 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 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 that how much effort is required in each of these options and what are pros and cons of each option.



How to get 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 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.


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 on our day to day life. You must remember that month in 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 10 Edition by Cay S. Horstmann.



Using Joda-Time:
Here is our second solution of this problem using Joda-Time library. This time, we are using the LocalDate class, similar to LocalDate of JDK 8, which also represent 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 in your project.


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



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 new Date and Time API of Java 8, please read Java SE 8 for Really Impatient By Cay S. Horstmann. One of the best book to learn new features on Java SE 8 in quick time.

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


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

Here is our sample program to find a number of year and months between two given dates using all three ways. The code is 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 year 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 read Java SE 8 for Programmers to learn more about new date and time API of Java 8.


Other Date and Time tutorials for Java Programmers
  • 20 example 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)


References
Calendar in Java SE 8
Joda-Time library




No comments :

Post a Comment