Compute days between 2 datesTag(s): Date and Time


One technique is to compute by hand the number of milliseconds between two dates and then convert the result in days.
import java.util.*;


public class DateUtils {
  private DateUtils() {  }

  static final long ONE_HOUR = 60 * 60 * 1000L;
  public static long daysBetween(Date d1, Date d2){
    return ( (d2.getTime() - d1.getTime() + ONE_HOUR) /
                  (ONE_HOUR * 24));
  }

  /*
     testing
  */
  public static void main(String[] args) {
    java.text.SimpleDateFormat sdf =
      new java.text.SimpleDateFormat("yyyyMMdd");
    Calendar first = Calendar.getInstance();
    first.set(2008, Calendar.AUGUST, 1);
    Calendar second = Calendar.getInstance();

    System.out.println
    (daysBetween(first.getTime(),second.getTime())
        + " day(s) between "
        + sdf.format(first.getTime()) + " and "
        + sdf.format(second.getTime()));
    /*
     * output :
     *   21 day(s) between 20080801 and 20080822
     */
  }
}
NOTE: The daysBetween() method works only on Dates set at midnight. One hour (known as the "fudge" factor) is added to the 2 Dates passed as parameters to take in account the possible DLS (Day Light Saving) one hour missing.

Another way would be to compute the julian day number of both dates and then do the substraction. See this HowTo. Thanks to P. Hill for the tip.


The package java.util.concurrent.TimeUnit; provides a class to make conversion between milliseconds and days easier.

import java.util.*;
import java.util.concurrent.TimeUnit;

public class DateUtils {
  private DateUtils() {  }

  public static long getDifference(Calendar a, Calendar b, TimeUnit units) {
    return
       units.convert(b.getTimeInMillis() - a.getTimeInMillis(), TimeUnit.MILLISECONDS);
  }

  /*
    testing
  */
  public static void main(String[] args) {
    java.text.SimpleDateFormat sdf =
        new java.text.SimpleDateFormat("yyyyMMdd");
    Calendar augustfirst2008 = Calendar.getInstance();
    augustfirst2008.set(2008, Calendar.AUGUST, 1);  // 2008-08-01
    Calendar today = Calendar.getInstance();        // today

    System.out.println
    (getDifference(augustfirst2008,today,TimeUnit.DAYS)
        + " day(s) between "
        + sdf.format(augustfirst2008.getTime()) + " and "
        + sdf.format(today.getTime()));
  }
    /*
     * output :
     *   921 day(s) between 20080801 and 20110208
     */
}

blog comments powered by Disqus