Java calculate difference between two dates

Basically you have to get the Calendar instance of the given dates and then find the difference in milli seconds. Once you have the milli seconds then you can easily convert that to days, hours, minutes and seconds. Here is an example ...
package com.as400samplecode;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateDifference {

 public static void main(String[] args) {

  //Specify the data format 
  DateFormat df = new SimpleDateFormat("yyyyMMdd");
  String fromDate = "20120607";
  String toDate = "20120913";
  long diff = 0;
  
  try {
   
   //Convert to Date
   Date startDate = df.parse(fromDate);
   Calendar c1 = Calendar.getInstance();
   //Change to Calendar Date
   c1.setTime(startDate);

   //Convert to Date
   Date endDate = df.parse(toDate);
   Calendar c2 = Calendar.getInstance();
   //Change to Calendar Date
   c2.setTime(endDate);
   
   //get Time in milli seconds
   long ms1 = c1.getTimeInMillis();
   long ms2 = c2.getTimeInMillis(); 
   //get difference in milli seconds
   diff = ms2 - ms1;
 
  } catch (ParseException e) {
   e.printStackTrace();
  }
  
  //Find number of days by dividing the mili seconds
  int diffInDays = (int) (diff / (24 * 60 * 60 * 1000));
  System.out.println("Number of days difference is: " + diffInDays);
  
  //To get number of seconds diff/1000
  //To get number of minutes diff/(1000 * 60)
  //To get number of hours diff/(1000 * 60 * 60)
  
 } 
 
}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.