programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Calculate date difference [Gregorian calender]

Bas Broeders
Greenhorn
Posts: 3
I'm sorry for this double-post, but I think this topic shouldn't have been posted in the beginners section.
The question was:
Hoe do I calculate the difference between 2 given dates? For example:
The input is 02-02-2001 and 02-01-2002
then the difference is 11 months.
How do I calculate this difference using the Gregorian Calender? (please give a code example)

Jim Yingst
Wanderer
Sheriff
Posts: 18671
Preferably, by avoiding the GregorianCalendar entirely. Aside from being needlessly complex, it doesn't actually have methods which will help you - except in the most ineffecient manner possible, which we won't get in to.
All you need is a SimpleDateFormat to parse the date (European style, apparently), plus the Date class and some simple math:

I calculated days rather than months since there is no single precise definition of how long a "month" is. You should of course adapt this to your needs.
This would probably have fit better in "Intermediate" than either Beginner or Advanced - but I don't really feel like moving it again.
[ February 05, 2002: Message edited by: Jim Yingst ]

Dirk Schreckmann
Sheriff
Posts: 7023
Hello,
You might consider that many of the methods of the Date class have been deprecated, and consider looking to the DateFormat class and perhaps the Calendar class. The DateFormatSymbols class might also contain something of use for you.
Good Luck,
-Dirk Schreckmann
[ February 06, 2002: Message edited by: Dirk Schreckmann ]

Jim Yingst
Wanderer
Sheriff
Posts: 18671
No - many specific methods (and even constructors) in Date have been deprecated. But the class as a whole has not been deprecated. In fact, the parse(String) method of DateFormat returns... a Date! As shown above.

Dirk Schreckmann
Sheriff
Posts: 7023
Crazy Me!
Obviously, you're right. I stated that incorrectly. It's correct now.
Thank You