Find difference between two dates in java with example.

How  to calculate no of days between two dates in Java:
       Difference between two dates can be calculated in many ways . I have calculated in two methods. One is using Java Util.Date and another is using Calendar class.
Method 1 :
1) Input two dates (dd/mm/yyyy) as a string using keyboard.
2) Convert the Dates String to Date format using DateFormat Class.
3) Calculate difference of two dates using Date getTime() method which returns the number of milliseconds since January 1,1970,00:00:00 GMT represented by this Date object
import java.io.*;
import java.util.*;
import java.text.*;

public class DateDiff  {
      public static void main(String [] args){
      try{
      BufferedReader br = new BufferedReader(
                  new InputStreamReader(System.in));

      DateFormat df = new SimpleDateFormat (“dd/MM/yyyy”);

      System.out.println(“Enter Date1”);

      String dateSt1= br.readLine();       // Accepts date1 as string

      System.out.println(“Enter Date2”); 

      String dateSt2= br.readLine();  // Accepts date2 as string

 Date date1=df.parse(dateSt1);     // Date String to Date
 Date date2=df.parse(dateSt2);
 
System.out.println(“Date1 = ” + dateSt1);
System.out.println(“Date2 = ” + dateSt2);

System.out.println(“Days between Date1 and Date2 = ” + (date2.getTime() – date1.getTime())/(24*60*60*1000));

      }
      catch(Exception e){
        System.out.println(“Error : Invalid Date “);
      }
  }

Running the above progrm
1) java DateDiff
Enter Date1
01/01/2011
Enter Date2
11/06/2011
Date1 = 01/01/2011
Date2 = 11/06/2011
Days between Date1 and Date2 = 161
2) java DateDiff
Enter Date1
10/06/2011
Enter Date2
11/06/2011
Date1 = 10/06/2011
Date2 = 11/06/2011
Days between Date1 and Date2 = 1
3) java DateDiff
Enter Date1
30/07/2011
Enter Date2
10/06/2011
Date1 = 30/07/2011
Date2 = 10/06/2011
Days between Date1 and Date2 = -50
———————————————————–
Method II :
1) Inputing two dates using Scanner Class with Delimiter “/” so that we can parse the date string to day , month , year integer.
2) Calender Class’s set method is used to convert into Date format using day, month, year , hour, min, second.
3) Calculate difference of two dates using Date getTime()
4) Calculate difference of two dates using the user defined function day();
import java.util.*;
import java.text.*;
import java.io.*;
public class DateDiffCal{
  public static void main(String args[]){

Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
   
    int day1=0;
    int month1=0;
    int year1=0;
 
    int day2=0;  
    int month2=0;
    int year2=0;

try{

System.out.println(“Enter Date 1”);

Scanner s = new Scanner(System.in).useDelimiter(“[/\s]”);  //Input for Date 1
    
      day1= s.nextInt();
      month1 = s.nextInt();
      year1 = s.nextInt();

System.out.println(“Date1   : ” + day1 + “/” + month1 + “/”  + year1);

System.out.println(“Enter Date 2”);

 s = new Scanner(System.in).useDelimiter(“[/\s]”);  //Input for Date 2

    
      day2= s.nextInt();
      month2 = s.nextInt();
      year2 = s.nextInt();

System.out.println(“Date2   : ” + day2 + “/” + month2 + “/”  + year2);

   
} catch (Exception e)
  {

 System.out.println(“Error: Invalid Date”);
   }
 

     cal.set(year1 , month1-1, day1 , 12, 0,0);

     cal1.set(year2 , month2-1, day2, 12,0,0 );

long Days=(cal1.getTime().getTime()-cal.getTime().getTime())/(24*3600*1000);

System.out.println(“Number of Days between ” +   new SimpleDateFormat(“dd/MM/yyyy”).format(cal.getTime().getTime()) + ” and ” + new

SimpleDateFormat(“dd/MM/yyyy”).format(cal1.getTime().getTime()) + ” = ” + Days);

Days=days(cal,cal1);
System.out.println (“Days Calculated by  user defined function days() : “+Days);

}

public static long days(Calendar date1, Calendar date2) { 

Calendar temp;
boolean negative=false;
  long days = 0; 

if(date1.after(date2))                           //Swap date if date1 is greater than date2..
 {

 negative=true;
 temp=date1;
 date1=date2;
 date2=temp;
 }

  while (date1.before(date2))
       { 
    date1.add(Calendar.DAY_OF_MONTH, 1); 
    days++; 
        } 

if(negative)
 {
   return -days; 
 }
else
 {
 return days;
 }

}

Running the above Program
  
1) java DateDiffCal
Enter Date 1
01/01/2011
Date1 : 1/1/2011
Enter Date 2
11/06/2011
Date2 : 11/6/2011
Number of Days between 01/01/2011 and 11/06/2011 = 161
Days Calculated by user defined function days() : 161
2) java DateDiffCal
Enter Date 1
10/06/2011
Date1 : 10/6/2011
Enter Date 2
11/06/2011
Date2 : 11/6/2011
Number of Days between 10/06/2011 and 11/06/2011 = 1
Days Calculated by user defined function days() : 1
3) java DateDiffCal
Enter Date 1
30/07/2011
Date1 : 30/7/2011
Enter Date 2
10/06/2011
Date2 : 10/6/2011
Number of Days between 30/07/2011 and 10/06/2011 = -50
Days Calculated by user defined function days() : -50

Leave a Reply

cbd industry growth where to buy cbd in atlanta cbd in illinois cbd legal in us cbd and liver enzymes how much cbd for pain relief is cbd medical marijuana cbd house cbd oil for diabetes type 2 cbd bronchodilator family lawyer sydney cbd what is good cbd oil to take cbd oil santa barbara cbd in missouri abilify and cbd oil cbd oil and metastatic breast cancer sensi chew cbd gold cbd and liver cancer can federal employees use cbd does cbd oil help plantar fasciitis cbd states legal hemp or cbd oil best cbd pills for anxiety uws parramatta cbd hookah cbd cbd vs thc effects cbd roll on for anxiety natures ultra cbd discount code what can cbd do for me dea cbd oil schedule 1 cannabis crystals cbd wholesale cbd oil cost does cbd show up on a hair test can cbd oil give you a headache bees knees cbd coupon cbd oil sold in san antonio cbd cbd oil where to buy cbd oil in lansing mi cbd oil slidell louisiana cbd receptors in the body cbd oil children seizures cbd oil for vulvodynia can you test positive from cbd oil is cbd oil illegal in idaho anti cbd oil for epilepsy best online cbd store calmong pain cbd oil spray triethyl citrate cbd cbd oil good for eczema sisters of the valley cbd where to get cbd oil newr me active ingredient in cbd oil cbd products for horses pellets or oil dr chad clause cbd oil

low glycemic diet for weight loss diet for a teenager to lose weight hcg diet drops for weight loss free keto diet menu and recipes diet plan chart for weight loss where to buy keto rapid diet pills the best pill to lose weight fast how to lose weight without exercising or dieting safe diet supplements to lose weight the best weight loss pill ketobliss diet pills reviews huel only diet weight loss healthy diet to lose weight endometriosis weight loss diet apples to lose weight fast diet dash diet weight loss solution grocery list diet for a day to lose weight what is the best weight loss pill sold at gnc easiest way to lose weight wthout dieting strict food diet lose weight apple cider vinegar weight loss pills reviews low protein diet weight loss weight loss supplements best 3 week diet weight loss weight loss supplement gnc best best weight loss pills appetite suppressant snack the bean diet for weight loss which diet is the best to lose weight fast 1600 calorie diet meal plan for weight loss 3 day liquid diet weight loss results weight loss pills of the stars keto ultra diet pills shark tank episode best fiber pills to take for weight loss no s diet to maintain weight loss cod liver oil pills weight loss ripped fuel weight loss pills weight loss and aip diet reduce weight loss through diet a diet for weight loss diabetic diet meal plan to lose weight paleo diet reddit weight loss can you take diet pills on keto cheap diet for weight loss illegal weight loss pills list 2500 calorie diet for weight loss 40 40 20 tortillas on mcdougall maximum weight loss diet how to maximize weight loss on a low carb diet weight loss exercise vs diet lose weight without dr fast pills algae pills for weight loss diurex pills to lose weight high starch diet weight loss does energy pills help lose weight quick weight loss pills india 2020

best get hard pills reaction to male enhancement pills xanogen male enhancement review are ed supplements safe v male enhancement mens libido booster gnc natural male enhancement fruits rhino number 7 sex enhancement ciarex male enhancement formula night bullet male enhancement for sale alphamax 10 male enhancement maca for male penis enlargement amberzine male enhancement dhea pills cvs copd and male enhancement pill can male enhancement pills cause headaches go male enhancement supplement herbal male supplements red pill for male enhancement nature male enhancement how is a penis enlargement done drugs that make you pass out instantly blue pill oval swag male enhancement reviews natural pill pain pill names how to buy pain pills pernament penis enlargement buy ed drugs online breast enhancers at walmart versele pills for erectile dysfunction compare male enhancement what are the side effects of the pill blue chewable ed pills erection enhancement drugs best male butt enhancer male enhancement blogroll 2002 best herbal male enhancement pills for ed beat it up male enhancement reviews zyflex male enhancement reviews super t supplement sex drive pills male x 15 male enhancer chinese sex pills in gas station 6 to 8 inches penis enlargement m patch male enhancement supplement do corner stores sex pills work fix penis enlargement turkey neck superstar male enhancement sex pills zinc pills sex number one selling male enhancement pill male enhancement with planteen biogenix male enhancement pills that work alpha dietary supplement