Calculating days between two dates with in java

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";

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *