Java Data Type How to - Difference between two particular dates








Question

We would like to know how to difference between two particular dates.

Answer

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/*from   w w  w.  ja  v  a2s . c o  m*/
public class Main {
   public static void main(String[] args) throws ParseException {
      String dateOne = "20-03-2014 16:14:13 GMT";
      String dateTwo = "25-03-2015 23:11:19 GMT";
      String format = "dd-MM-yyyy HH:mm:ss z";
      System.out.println(getDiff(parseDateString(format, dateTwo), 
                  parseDateString(format, dateOne)));
   }
   static Calendar parseDateString(final String format, 
                  final String date) throws ParseException {
      final Date parsed = new SimpleDateFormat(format).parse(date);
      final Calendar cal = Calendar.getInstance();
      cal.setTime(parsed);
      return cal;
   }
   private static TimeDiff getDiff(final Calendar calOne, final Calendar calTwo) {
      return new TimeDiff(Math.abs(calOne.getTimeInMillis() - calTwo.getTimeInMillis()));
   }  
}
class TimeDiff {
  private static final long MS_IN_SECOND = 1000;
  private static final long MS_IN_MINUTE = MS_IN_SECOND * 60;
  private static final long MS_IN_HOUR = MS_IN_MINUTE * 60;
  private static final long MS_IN_DAY = MS_IN_HOUR * 24;
  private final long days;
  private final long hours;
  private final long minutes;
  private final long seconds;
  private final long milliseconds;
  TimeDiff(final long msDiff) {
     long msRemainder = msDiff;
     days = msRemainder / MS_IN_DAY;
     msRemainder = msRemainder - (days * MS_IN_DAY);
     hours = msRemainder / MS_IN_HOUR;
     msRemainder = msRemainder - (hours * MS_IN_HOUR);
     minutes = msRemainder / MS_IN_MINUTE;
     msRemainder = msRemainder - (minutes * MS_IN_MINUTE);
     seconds = msRemainder / MS_IN_SECOND;
     msRemainder = msRemainder - (seconds * MS_IN_SECOND);
     milliseconds = msRemainder;
  }
  @Override
  public String toString() {
     return "TimeDiff[days: " + days + ", hours: " + 
              hours + ", minutes: " + minutes + 
              ", seconds: " + seconds + ", milliseconds: " + 
              milliseconds + "]";
  }
}

The code above generates the following result.