How to Calculate the Number of Days Between Two Dates in Java

In this tutorial, we are going to see how to calculate the number of days between two dates in Java.

Program to calculate the number of days between two dates in Java:

In this program, we have the dates as strings. We first analyze them as dates and then calculate the difference in milliseconds. Next, we convert the milliseconds to days and display the result as output.

import java.util.Date;
import java.text.SimpleDateFormat;

public class DateExemple{
   public static void main(String args[]){
	 SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
	   try {
	        Date dateAvant = sdf.parse("02/25/2012");
	        Date dateApres = sdf.parse("03/31/2012");
	        long diff = dateApres.getTime() - dateAvant.getTime();
	        float res = (diff / (1000*60*60*24));
	        System.out.println("Number of days between the two dates is: "+res);
	   } catch (Exception e) {


Number of days between the two dates is: 35.0



We recommend that you use Joda Time, a much better API than the Date class found in JAVA 8. You can use the following statement:

 int days = Days.daysBetween(date1, date2).getDays();
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *