javadatetimecalendarsimpledateformattimeunit

Converting difference between 2 dates to days in java 7


I want to compare 2 dates in java and need to convert the difference between the 2 dates to days

//Setting up date
Calendar cal = Calendar.getInstance();
cal.set(2019, 5, 16);
Date d = cal.getTime();

Output would be something like this : Sun Jun 16 11:04:57 UTC 2019

//Getting the current date instance
Calendar cal1 = Calendar.getInstance();
Date d1 = cal1.getTime();

Output would be something like this : Mon Jul 08 11:04:57 UTC 2019

Need to get the difference between d & d1 in days.

Thanks in advance for taking your time to provide solution


Solution

  • Here, you just have to do simple math.

    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    start.set(2010, 7, 23);
    end.set(2010, 8, 26);
    Date startDate = start.getTime();
    Date endDate = end.getTime();
    long startTime = startDate.getTime();
    long endTime = endDate.getTime();
    long diffTime = endTime - startTime;
    long diffDays = diffTime / (1000 * 60 * 60 * 24);
    DateFormat dateFormat = DateFormat.getDateInstance();
    System.out.println("The difference between "+
      dateFormat.format(startDate)+" and "+
      dateFormat.format(endDate)+" is "+
      diffDays+" days.");
    

    This will not work when crossing daylight savings time (or leap seconds) and might as well not give the expected results when using different times of day. You can modify it like this:

    start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
    while (start.before(end)) {
        start.add(Calendar.DAY_OF_MONTH, 1);
        diffDays++;
    }
    while (start.after(end)) {
        start.add(Calendar.DAY_OF_MONTH, -1);
        diffDays--;
    }
    

    Hope this helps. Good luck.