38

Possible Duplicate:
how to calculate difference between two dates using java

I'm trying something like this, where I'm trying to get the date from comboboxes

Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();  

int Sdate=Integer.parseInt(cmbSdate.getSelectedItem().toString());  
int Smonth=cmbSmonth.getSelectedIndex();
int Syear=Integer.parseInt(cmbSyear.getSelectedItem().toString());  

int Edate=Integer.parseInt(cmbEdate.getSelectedItem().toString());
int Emonth=cmbEmonth.getSelectedIndex();
int Eyear=Integer.parseInt(cmbEyear.getSelectedItem().toString());

start.set(Syear,Smonth,Sdate);  
end.set(Eyear,Emonth,Edate);

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String startdate=dateFormat.format(start.getTime());  
String enddate=dateFormat.format(end.getTime());

I'm not able to subtract the end and start date How do I get the difference between the start date and end date??

Community
  • 1
  • 1
Charanraj Golla
  • 1,102
  • 3
  • 17
  • 35
  • how you are not able? Exception? Wrong date? – Bozho Sep 26 '10 at 06:58
  • I'm trying to do this program in netbeans n i tried to subtract d end.getTime-start.getTime() n I was notified that it was possible to use - operator between the two Date obj. – Charanraj Golla Sep 26 '10 at 07:46
  • Why I cannot add my answer? I have no a question like this, I have another solution for this question. – Radio Rogal Jan 13 '15 at 16:48
  • May be because the question is marked as duplicate. – Charanraj Golla Jan 16 '15 at 04:14
  • Modern comment: I recommend you don’t use `Calendar` and `SimpleDateFormat`. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Instead use `LocalDate` and `ChronoUnit.DAYS`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 27 '19 at 07:30

3 Answers3

48
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) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java before 8 I know is to use Calendar's add and before/after methods to check and adjust the calculation:

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--;
}
hd42
  • 1,741
  • 15
  • 30
  • 2
    can you please explain me about this piece of code:1000 * 60 * 60 *24 – Charanraj Golla Sep 26 '10 at 11:42
  • 1
    Date.getTime returns time since 1970 in milliseconds, so the difference is also in milliseconds. 1000 milliseconds make 1 second, 60 seconds make 1 minute, 60 minutes make 1 hour and 24 hours make 1 day. Of course you could just divide diffTime by 86400000, but then you wouldn't see as clearly (ok, obviously still not clearly enought ;) ), what that number is. – hd42 Sep 26 '10 at 15:31
  • 10
    NOTE Will be incorrect for date ranges that cross daylight savings time boundary. – jpswain Jun 28 '11 at 04:14
  • 3
    I have face same problem, but i found lengthy codes which are very ineffective I think. Though this is a duplicate and old one, I found a easy way try this `public static long getTimeDiff(Date dateOne, Date dateTwo) { long diff = 0; long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime()); diff = TimeUnit.MILLISECONDS.toDays(timeDiff); return diff; }` – Ruwanka De Silva Dec 27 '13 at 06:47
  • @orange80 Though it's pretty late, can you please give an example when this fails. I've searched a lot but couldn't find any date ranges for which this fails. Thank you. – abhilash Jul 28 '14 at 11:14
  • 2
    @abhilash take for example start.set(2014, Calendar.MARCH, 8) and end.set(2014, Calendar.APRIL, 8); When I run this (in Germany crossing DST on March 30th, in USA crossing DST on March 9th), I get a difference of 30 days without the fix inspired by orange80's comment and the correct 31 days with it. If you run this on a computer with the Locale set to India, there will probably be no difference as India does not seem to have daylight savings time (according to http://www.timeanddate.com/time/dst/2014.html) – hd42 Jul 29 '14 at 18:42
  • @hd42 Thanks for your reply. I've tested this by setting Calendar instance as 'Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"))' and felt so happy when my test case failed! Thanks again. – abhilash Jul 31 '14 at 06:27
  • I can able add my answer but I found another solution to find day difference without [JodaTime](http://joda-time.sourceforge.net/). See http://stackoverflow.com/questions/14269495/finding-days-difference-in-java/27927538#27927538 – Radio Rogal Jan 13 '15 at 17:10
  • @jpswain To fix the date ranges that cross daylight savings time boundary, use: `TimeZone timezone = start.getTimeZone(); long diffTime = endTime - startTime + timezone.getOffset(endTime) - timezone.getOffset(startTime);` – Fabi Feb 14 '19 at 15:56
25

Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:

private static void dateDiff() {

    System.out.println("Calculate difference between two dates");
    System.out.println("=================================================================");

    DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    System.out.println("  Difference between " + endDate);
    System.out.println("  and " + startDate + " is " + days + " days.");

  }
Faisal Feroz
  • 12,458
  • 4
  • 40
  • 51
  • 2
    Thanx for the answer mr. Faisal but i need to use only the built in functions and apis – Charanraj Golla Sep 26 '10 at 07:35
  • 2
    Now that Java 8 has basically the same constructs as Joda Time, you can do this with a java.time.LocalDateTime and a ChronoUnit.DAYS.between(startDate,endDate); – Ben L. Jan 05 '19 at 17:19
18

Like this.

import java.util.Date;
import java.util.GregorianCalendar;

/**
 * DateDiff -- compute the difference between two dates.
 */
public class DateDiff {
  public static void main(String[] av) {
    /** The date at the end of the last century */
    Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();

    /** Today's date */
    Date today = new Date();

    // Get msec from each, and subtract.
    long diff = today.getTime() - d1.getTime();

    System.out.println("The 21st century (up to " + today + ") is "
        + (diff / (1000 * 60 * 60 * 24)) + " days old.");
  }

}

Here is an article on Java date arithmetic.

Community
  • 1
  • 1
rics
  • 5,494
  • 5
  • 33
  • 42