programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Paul Clapham
• Ron McLeod
• Jeanne Boyarsky
• Tim Cooke
Sheriffs:
• Liutauras Vilda
• paul wheaton
• Henry Wong
Saloon Keepers:
• Tim Moores
• Tim Holloway
• Stephan van Hulst
• Carey Brown
• Frits Walraven
Bartenders:
• Piet Souris
• Himai Minh

# calculate difference in months

Greenhorn
Posts: 11
• Number of slices to send:
Optional 'thank-you' note:
How to calculate difference in months between 2 dates?

(instanceof Sidekick)
Posts: 8791
• Number of slices to send:
Optional 'thank-you' note:
I think that's going to lead to the question of what is a month? 365.25/12 days? What's a month before March 30? Two months before March 30? Does (March 30 - 2 months) == (March 30 - 1 month - 1 month)?
Now that I'm confused (how about you?) GregorianCalendar class has an add method that lets you specify +-n of some unit. See if it will take month as the unit. Then try those cases above and see if you like the results!

Ranch Hand
Posts: 59
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by dhanu sudha:
How to calculate difference in months between 2 dates?

hi Dhanu Sudha,
Try this. Code is pretty self-explainatory.
Regards,
Vinod.
import java.util.GregorianCalendar;
public class CalPractice {
public static void main(String[] args) {
GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.set(2003, 10, 10);
c2.set(2003, 10, 6);
System.out.println((c1.getTimeInMillis() - c2.getTimeInMillis())/86400000);
}

}

Ranch Hand
Posts: 688
• Number of slices to send:
Optional 'thank-you' note:
Almost the same as Vinod Chandana's code

Stan James
(instanceof Sidekick)
Posts: 8791
• Number of slices to send:
Optional 'thank-you' note:
Oops, I failed to read the question, didn't I? My rant was off topic - about how to add or subtract months to dates. There are "officially correct" answers to all those questions I threw out. But this is tricky enough to use somebody else's solution rather than write one.
Still, ask yourself what the results of the calculations above mean ... what is "exactly two months"? Same day-of-month two months ago? Or 59 or60 days ago (Jan + Feb)?

 This one time, at bandcamp, I had relations with a tiny ad. Free, earth friendly heat - from the CodeRanch trailboss https://www.kickstarter.com/projects/paulwheaton/free-heat
reply