# How to Calculate Difference between two Dates in Java (In Days) - Example Tutorial

If you are not running on Java 8, then there are two ways to calculate the difference between two dates in Java in days, either by using standard JDK classes e.g. java.util.Date and java.util.Calendar or by using the joda-time library. Unfortunately, Java's old Date and Calendar API is buggy and not intuitive, so many of us by default use Joda for all date and time arithmetic. In this example, you will learn how to find the number of days between today and any date entered by a user using Joda, as well as without using any third-party library. When I first time face this problem, I thought what's a big deal about finding the difference between dates? If you can convert Date to milliseconds then finding a number of days, months or years are just a matter of simple arithmetic, but I was WRONG. I was not thinking about the real-world date and time nuisance like leap seconds, leap years, and daylight saving time.

It's very difficult to accurately calculate the difference between two dates in Java without using a third-party library unless you have time to develop your own library like Joda, which diligently takes these things into consideration. Thankfully, you don't need to worry because Java 8 got lucky the third time.

There is a new Date and Time API which has corrected previous mistakes and turns out to be a real gem. If you are keen to learn Java 8, not just this API, I suggest you grab a copy of Java 8 in Action, one of the better books to learn new features of Java 8 in quick time.

## How to find the number of days between two dates in Java?

Since java.util.Date class implements Comparable interface it's easy to figure out whether a date comes before or after another date, or whether two dates are equal to each other as shown here, but when it comes to finding out how many days between two dates? we don't have a simple method like daysBetween(date1, date2) in the JDK library.

Unfortunately, this is a quite common requirement, as you may need to find days between today and your next birthday, or how many days to your next insurance premium from today, or simply how many days between the last two cricket world cups. In fact, calculating date and time difference is the most common date arithmetic in Java.

In this article, we will see two ways to solve this problem, first by using JDK, without using any third-party library, and second by using the joda-time library.

### How to find the difference between two dates in Java?

Though all is not lost, you can quickly write a simple routine to find the difference between two dates in terms of days in Java. How? By converting a date to milliseconds. Once you have milliseconds, you can just subtract them and then again divide them by 86400000 (milliseconds per day)

This way you will get exactly how many days between two dates in Java. How will you get milliseconds from a date in Java? by using the getTime() method of java.util.Date class, as shown below :

``` private static long daysBetween(Date one, Date two) {
long difference =  (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}```

This will work 99% of the time, but just like any quick and dirty solution, it will not handle any special cases e.g. time or timezone, leap years, or daylight saving time. It will fail on summer boundaries when daylight changes occur.

A better solution is to use a tried and tested date and time library like Joda-Time, which handles those tricky scenarios much better. Alternatively, you can also use new java.time classes from Java 8, which are heavily influenced by the joda-time library. See Java SE 8 for Really Impatient book by Cay S. Horstmann for more details.

BTW, if you are using JDK 8 then you and use java.time.Period class to calculate the difference between two dates in Java. Here is an example of calculating the date and time difference in Java 8, it's super easy and not error-prone like earlier API. There is another class called, java.time.Duration, which is good to calculate a time difference between two instants.

### How to calculate days between two dates using joda-time in Java?

In order to solve this problem using joda-time, we need to use a class called LocalDate to represent your dates. It is similar to the LocalDate class of Java 8, or should I say LocalDate is inspired by this class.  This class knows about the weirdness we just talked about, e.g. some timezones don't have days that start at midnight.

You can calculate the difference between two dates in joda by using static utility class Days, which has method daysBetween() to return the number of days between two given dates as shown in the following example :

``` public static int daysBetweenUsingJoda(Date d1, Date d2){
return Days.daysBetween(
new LocalDate(d1.getTime()),
new LocalDate(d2.getTime())).getDays();
}```

You can see that Days.daysBetween() method accepts a LocalDate and its's very easy to convert an instance of java.util.Date to org.joda.time.LocalDate class, just pass a number of milliseconds to it.

### Dependency for Joda Time library

Joda-Time requires Java SE 5 or later and has no dependencies. There is a compile-time dependency on Joda-Convert, but this is not required at run-time thanks to the magic of annotations. You can download joda-time-2.5.jar either from Maven central or directly from the http://www.joda.org/joda-time/ website. If you are using Maven then you can also add the following dependency into your pom.xml file :

```<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.5</version>
</dependency>```

If you download the JAR file then make sure you add joda-time-2.5.jar in your Java program's classpath and you are done.  If you are not sure how to do that, see this tutorial.

## Difference between two dates in a number of Days - Example

Here is our full Java program to find out how many days between two dates in Java using standard JDK classes and by using the open source Joda Time library. I have name aptly named our program "date diff", as its calculating difference between dates.

```import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

import org.joda.time.Days;
import org.joda.time.LocalDate;

/**
* Java Program to find number of days between two dates in Java.
* This program calculate difference between two dates in days using two ways
* without using third party library and by using joda-time library.
*
* @author WINDOWS 8
*/

public class DateDiffExample {

private static final DateFormat df = new SimpleDateFormat("yyyy/MM/dd");

public static void main(String args[]) throws ParseException{

System.out.println("Please enter two dates in format yyyy/MM/dd to compare");

Date one = getDate(first);
Date two = getDate(second);

// quick and dirty way, work but not in all conditions
// you can convert date into milliseconds then subtract
// them and again convert it to days
long numberOfDays = daysBetween(one, two);
System.out.printf("Number of days between date %s and %s is : %d %n",
first, second, numberOfDays);

// a better way to calculate difference between two dates in Java
// is by using JodaTime library as shown below
int differenceBetweenDates = daysBetweenUsingJoda(one, two);
System.out.printf("difference betweeen two dates %s and %s is : %d %n",
first, second, differenceBetweenDates);

}

/*
* Simple way to parse String to date in Java
*/
private static Date getDate(String date) throws ParseException{
return df.parse(date);
}

/*
* Java Method to calculate difference between two dates in Java
* without using any third party library.
*/
private static long daysBetween(Date one, Date two) {
long difference =  (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}

/*
* Java Method to find number of days between two dates
* in Java using JodaTime library. To find difference
* we first need to convert java.util.Date to LocalDate
* in JodaTime.
*/
public static int daysBetweenUsingJoda(Date d1, Date d2){
return Days.daysBetween(
new LocalDate(d1.getTime()),
new LocalDate(d2.getTime())).getDays();
}
}

Output:
Please enter two dates in format yyyy/MM/dd to compare
2014/11/23
2014/11/25
Number of days between date 2014/11/23 and 2014/11/25 is : 2
difference between two dates 2014/11/23 and 2014/11/25 is : 2

```

You can see that number of days between two dates is correct and the output of both our own method and joda-time is the same.

That's all about how to find a number of days between two dates in Java. I will advise you to use our quick and dirty solution, only if you are doing it for learning purposes like homework, school assignments, or college projects. For real-world things, I would suggest either using the joda-time library if you are running on Java 6 or 7 or using the new Java 8 date and time API if you are running on JDK 8.

There is no reason for not using the new Date and Time API if you are running in Java 8, and there is no way not to use joda-time for previous Java versions. You can also calculate the number of months and years between two dates by using this technique.

If you like this tutorial and wants to learn more about both old and new Date, Time and Calendar API in Java, then check out my following tutorials :
• Difference between java.util.Date and java.sql.Date? [answer]
• How to convert String to Date using SimpleDateFormat in Java? [example]
• How to convert XMLGregorianCalendar to Date in Java? [example]
• How to parse Date in a thread-safe manner using Joda? [solution]
• Difference between java.sql.Time, java.sql.Timestamp and java.util.Date? [answer]
• How to get the current day, month, and year in Java? [example]
• How to add and subtract dates in Java? [solution]
• How to format Date and Time in Java SE 6? [example]

That's all about how to calculate the difference between two dates in Java. You can use the techniques and examples given in this tutorial to calculate a number of days between two given dates in Java.

Anonymous said...

In Java 8 you can do like this :

LocalDate difference = LocalDate.between(startDate, endDate, ChronoUnit.Days)

This will give you difference between two dates in number of days. You can further change ChronoUnit to to get the difference in terms of months, years, hours or any other time units.

Anonymous said...

Hello, how do we get number of months between two dates in Java? For example, one date is "22/03/2014" and other is "23/03/2015", how do you get months between them?

Swami said...

Right way to find difference between dates in terms of days, months and year is by using ChronoUnit class e.g.

long daysInBetween = ChronoUnit.DAYS.between(date1, date2);

long monthsInBetween = ChronoUnit.MONTHS.between(date1, date2);

long yearsInBetween = ChronoUnit.YEARS.between(date1, date2)

Cheers

javin paul said...

@Anonymous and @Swami, thanks for Java 8 examples. Indeed joda and Java 8 API is way to go, but its good to know how to do basic things with Date and Calendar as well.

Unknown said...

please How can I print the date on the file???
use this code

package javaapplication18;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.*;
public class JavaApplication18 {

public static void main(String args[]) {
//getting local time, date, day of week and other details in local timezone
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());

Date currentTime = localCalendar.getTime();
int currentDay = localCalendar.get(Calendar.DATE);
int currentMonth = localCalendar.get(Calendar.MONTH) + 1;
int currentYear = localCalendar.get(Calendar.YEAR);
int currentDayOfWeek = localCalendar.get(Calendar.DAY_OF_WEEK);
int currentDayOfMonth = localCalendar.get(Calendar.DAY_OF_MONTH);
int CurrentDayOfYear = localCalendar.get(Calendar.DAY_OF_YEAR);

System.out.println("Current Date and time details in local timezone");
System.out.println("Current Date: " + currentTime);
System.out.println("Current Day: " + currentDay);
System.out.println("Current Month: " + currentMonth);
System.out.println("Current Year: " + currentYear);
System.out.println("Current Day of Week: " + currentDayOfWeek);
System.out.println("Current Day of Month: " + currentDayOfMonth);
System.out.println("Current Day of Year: " + CurrentDayOfYear);

//getting time, date, day of week and other details in GMT timezone
//rest of stuff are same
}

}

Unknown said...

If you only need to know how many milliseconds, seconds, minutes, or hours passed since an event in your application, consider storing and comparing the system milliseconds instead of a Date or Calendar object. When you are timing timing events that are less than a single day, leap seconds and leap years are immaterial.

final long start = System.currentMillis();
// do complex calculations
final long duration = (System.currentMillis()-start)/1000;
System.out.println("My code took " + duration + " secs");

Even when you are measuring days between events, you probably are rounding off the fractional days anyway. In this case, you may also not really care about being accurate to the second, so again a leap second is immaterial to what you are measuring.

If you don't need the accuracy, then you should avoid the overhead of constructing Date and Calendar objects.

However, you may not be able to avoid constructing a Date object if you are storing dates as strings. In this case, be sure you know the time zone used to construct the date strings so you can load them correctly.
Date.toMilliseconds() returns the same long value regardless of time zone for equivalent dates that refer to the exact same point in time.

Anonymous said...

Sorry to say that but DAYS.between is wrong or buggy

Calculate: 2017-08-01 => 2022-08-01
DAYS.between says: 1857 days

Everybody else (online calulators, Excel, LibreOffice) says: 1826 days.

Strange ....

Koray GECICI said...

if you dont want to use standard java library or any 3rd pary you can calculate julian day.
You can have a look: https://www.koraygecici.com/en/java-articles/7-number-of-days-between-2-dates-algorithim