In this tutorial we will see how to calculate the number of days between two dates.
Program to find the number of Days between two Dates
In this program we have the dates as Strings. We first parses them into Dates and then finds the difference between them in milliseconds. Later we are convert the milliseconds into Days and displays the result as output.
Note: In Java 8 we can easily find the number of days between the given dates using a simple java method. Refer this Java 8 tutorial to check this program in Java 8
import java.util.Date; import java.text.SimpleDateFormat; class Example{ public static void main(String args[]){ SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy"); String dateBeforeString = "31 01 2014"; String dateAfterString = "02 02 2014"; try { Date dateBefore = myFormat.parse(dateBeforeString); Date dateAfter = myFormat.parse(dateAfterString); long difference = dateAfter.getTime() - dateBefore.getTime(); float daysBetween = (difference / (1000*60*60*24)); /* You can also convert the milliseconds to days using this method * float daysBetween = * TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS) */ System.out.println("Number of Days between dates: "+daysBetween); } catch (Exception e) { e.printStackTrace(); } } }
Output:
Number of Days between dates: 2.0
In the above example, we have the dates in the format of dd MM yyyy
and we are calculating the difference between them in days. If you have dates in the different format then you need to change the code a little bit. For example if you have the dates in this format “MM/dd/yyyy” then you need to replace the first three lines of the code (inside main method) with this code:
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy"); String dateBeforeString = "01/31/2014"; String dateAfterString = "02/02/2014";
Frank says
The above example does not factor daylight savings and leap years. Very important issue in the real world.
Carlos FC says
Try this case, and does not work (Java 6 u 35):
Calendar cal1 = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
cal1.set(2014, 3, 3);
cal2.set(2014, 3, 6);
System.out.println(“Days= “+ ( (cal2.getTime().getTime() – cal1.getTime().getTime()) / (1000 * 60 * 60 * 24)));
karan says
Above method is not giving correct output.
I have given dates “01-31-2014” and “02-02-2014”
output is -1 which is wrong.It should be 2.
Chaitanya Singh says
I have updated the guide with a new code. A new way to find the number of days between two dates.
Neeraj Kumar says
hi guys i am using this is code but here is some error.
String index out of range: 10
Chaitanya Singh says
Try the new code and let me know if you still face the issue.