aspose file tools*
The moose likes Java in General and the fly likes Calculate date difference [Gregorian calender] Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Calculate date difference [Gregorian calender] " Watch "Calculate date difference [Gregorian calender] " New topic
Author

Calculate date difference [Gregorian calender]

Bas Broeders
Greenhorn

Joined: Feb 05, 2002
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

Joined: Jan 30, 2000
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 ]

"I'm not back." - Bill Harding, Twister
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
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 ]

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
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

Joined: Dec 10, 2001
Posts: 7023
Crazy Me!
Obviously, you're right. I stated that incorrectly. It's correct now.
Thank You
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Calculate date difference [Gregorian calender]
 
Similar Threads
Factory Methods
Date Difference
Reading date from Oracle based on calendar
Date and time componet
String to Date???