| Author |
exact date difference using Gregorian Calendar
|
Udayan Kumar
Ranch Hand
Joined: Jan 16, 2007
Posts: 66
|
|
Hi there,
I am trying to find out the exact difference between two dates either in no.of.years or no.of.months. I am using the GregorianCalendar api for the same.
Here is the excerpt of the code
-----------------
while (gc1.before(gc2)) {
gc1.add(type,1); // type is Calendar.YEAR
elapsed++;
}
------------------
This always give the difference+1 as even when gc1 (yr or month) is the same as gc2 (yr or month) the while block executes. How can this be resolved using the GregorianCalendar api.
Do post your thoughts
Uday
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
|
Subtract 1 from the result.
|
 |
Arjan Kleene
Greenhorn
Joined: Mar 07, 2009
Posts: 4
|
|
|
If gc1.before(gc2) returns true even though month and year are equal, then that must mean that day of month and/or time are not equal. So you should check your code, particularly the parts related to setting gc1 and gc2. If you do not want to use time in your comparison, you should make sure it remains 0.
|
 |
Udayan Kumar
Ranch Hand
Joined: Jan 16, 2007
Posts: 66
|
|
Hi Arjan,
I am using gregorianCalendar.clear methods (if the request is month i clear the date) and when it is clear we clear the date and month.
Is this what you mentioned in your post.
Uday
|
 |
Arjan Kleene
Greenhorn
Joined: Mar 07, 2009
Posts: 4
|
|
|
When I tested the date comparison, I simply used the date in the constructor. Something like gc1 = new GregorianCalendar(2009, 1, 31); This sets hour, minute, second and millisecond to the default value (0). It doesn't take into account that you might have different timezones, but if you just want to know the number of days/months/years then timezone doesn't really matter. If you don't specify a timezone then the default timezone will be used. So you still get the same timezone for all dates.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
With years and months it's quite easy to calculate the difference. For years it is simply
For months it is similar:
This code does assume that each year has the same number of months though. If not you will have to loop:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
I forgot for a moment that months are 0 based, so should be changed into
The same code without the +1 can also be used for Calendar.DAY_OF_YEAR and Calendar.WEEK_OF_YEAR.
And finally the generic code for months, weeks and days:
The minimum will be 0 for months, 1 for weeks and days. The + 1 is required because both the maximum and minimum are inclusive. I've tested it and compared it to VisualBasic's DateDiff method, with equal results for all three fields.
|
 |
 |
|
|
subject: exact date difference using Gregorian Calendar
|
|
|