Link to home
Start Free TrialLog in
Avatar of de_britto
de_britto

asked on

How to use DateDiff function in Java?

All.,
How to use DateDiff function in Java? ie. How to find no of days/weeks/months between two dates in Java


Any help?


THanks in advance
Britto
ASKER CERTIFIED SOLUTION
Avatar of m_onkey_boy
m_onkey_boy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of m_onkey_boy
m_onkey_boy

int nDifferenceInWeeks =  c.get(Calendar.WEEK_OF_YEAR) - c2.get(Calendar.WEEK_OF_YEAR);

int nDifferenceInMonths =  c.get(Calendar.MONTH_OF_YEAR) - c2.get(Calendar.MONTH_OF_YEAR);
Hi as mentioned above

you can use calendar class

GregorianCalendar  class is direct implementation of Calendar class
 
refer to these links

http://www.jguru.com/search/results.jsp

http://www.esus.com/javaindex/j2se/jdk1.2/javautil/dates/dates.html


hope this helps
or you can do something like this (i'm not sure if this is in one of the posts above but it's what i use:

simply call getDateDiff(Calendar.<unit>, d1, d2);

       private static final double DAY_MILLIS = 1000*60*60 * 24.0015;
       private static final double WEEK_MILLIS = DAY_MILLIS * 7;
       private static final double MONTH_MILLIS = DAY_MILLIS * 30.43675;
       private static final double YEAR_MILLIS = WEEK_MILLIS * 52.2;

          public static int getDateDiff( int calUnit, java.util.Date d1, java.util.Date d2 ) {
           // swap if d1 later than d2
           boolean neg = false;
           if( d1.after(d2) ) {
              java.util.Date temp = d1;
              d1 = d2;
              d2 = temp;
              neg = true;
           }

           // estimate the diff.  d1 is now guaranteed <= d2
           int estimate = (int)getEstDiff( calUnit, d1, d2 );

           // convert the Dates to GregorianCalendars
           GregorianCalendar c1 = new GregorianCalendar();
           c1.setTime(d1);
           GregorianCalendar c2 = new GregorianCalendar();
           c2.setTime(d2);

           // add 2 units less than the estimate to 1st date,
           //  then serially add units till we exceed 2nd date
           c1.add( calUnit, (int)estimate - 2 );
           for( int i=estimate-1; ; i++ ) {        
              c1.add( calUnit, 1 );
              if( c1.after(c2) )
                 return neg ? 1-i : i-1;
           }
          }      

        private static int getEstDiff( int calUnit, java.util.Date d1, java.util.Date d2 ) {
           long diff = d2.getTime() - d1.getTime();
           switch (calUnit) {
           case Calendar.DAY_OF_WEEK_IN_MONTH :
           case Calendar.DAY_OF_MONTH :
     //      case Calendar.DATE :      // codes to same int as DAY_OF_MONTH
              return (int) (diff / DAY_MILLIS + .5);  
           case Calendar.WEEK_OF_YEAR :
              return (int) (diff / WEEK_MILLIS + .5);
           case Calendar.MONTH :
              return (int) (diff / MONTH_MILLIS + .5);
           case Calendar.YEAR :
              return (int) (diff / YEAR_MILLIS + .5);
           default:
              return 0;
           } /* endswitch */
        }
This functions returns the difference between two dates, in years, months, days, hours, minutes and
seconds. One year is assumed to be 365 days and a month 30 days.

public static void getDateDiff(int year1, int month1, int day1, int hour1, int minute1, int second1,
  int year2, int month2, int day2, int hour2, int minute2, int second2) {
  long date1 = (new GregorianCalendar(year1, month1 - 1, day1, hour1, minute1, second1)).getTime().getTime();
  long date2 = (new GregorianCalendar(year2, month2 - 1, day2, hour2, minute2, second2)).getTime().getTime();
  long diff = (date2 - date1) / 1000; // get the difference in seconds
  long daysDiff = diff / (60 * 60 * 24); // get the difference in days
  long years = daysDiff / 365;
  long months = daysDiff % 365 / 30;
  long days = daysDiff % 365 % 30;
  long hours = diff % (24 * 60 * 60) / (60 * 60);
  long minutes = diff % (60 * 60) / 60;
  long seconds = diff % 60;
  System.out.println("Years: " + years + ", Months: " + months + ", Days: " + days
     + ", Hours: " + hours + ", Minutes: " + minutes + ", Seconds: " + seconds);
}


Example call:

// get difference between '2001-03-26-14:17:04' and '2001-03-27-14:19:07'
getDateDiff(2001, 3, 26, 14, 17, 4, 2001, 3, 27, 14, 19, 7);

This will display:
Years: 0, Months: 0, Days: 1, Hours: 0, Minutes: 2, Seconds: 3
Just use Calendar.  It takes leap year into account and everything - even time zones.
Calendar is also smart enough to consider months with 30 or 31 days.  You never have to compromise accuracy this way.
I usually use the getTimeInMillis() method of the GC and then divide the milliseconds down into days. i.e.

int dayDiff;
GregorianCalendar gc1 = new GregorianCalendar( 2003, Calendar.FEBRUARY, 28);
GregorianCalendar gc2 = new GregorianCalendar( 2003, Calendar.MARCH, 31);

dayDiff = (int)((gc1.getTimeInMillis() - gc2.getTimeInMillis()) / (24*60*60*1000));


...oddly though this seems to give seems to yield a result of 1 day less than the same calculation in Excel for example (in this case 30 rather than 31).

If you are working with time as well then this will just perform integer rounding, but you could leave dayDiff as double to get the partial day difference as well.

cheers

Dan
In actual fact, it's a little odd that if you use these dates with the above method:
28/02/2003 and 31/03/2003
it returns 30 days, which to me would seem 1 short, but if you use:
28/02/2003 and 17/03/2003
it returns 17 days, which seems correct.

I have to admit I'm not too sure why this is.  I thought initially a rounding error but the double return value is 30.0

anyone know why this might be? (I don't mean to hijack the question, it's just that it might actually work for a solution if not for this problem).

Cheers
hey just go to http://www.javatutorials.org/javatutorials/index.html
and you'll find the source code to the program (there it is done the most elementary way possible)

good luck (although you've probably already figured it out by now)!

Nickbuds
Avatar of girionis
No comment has been added lately, so it's time to clean up this TA.

I will leave a recommendation in the Cleanup topic area that this question is:

- points to m_onkey_boy

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

girionis
Cleanup Volunteer