Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# how to get number of months between two given dates in java

kiran kumar
Greenhorn
Posts: 29
hi ,
how to get months difference between two given dates in java by using Date or Gregorian Calendar.
(like months_between(date1,date2) function in oracle.)

Jim Yingst
Wanderer
Sheriff
Posts: 18671
Well, I don't think there's any well-defined standard for what that would mean. The length of a month varies, after all. How many months are between Jan 31 and March 1? How many between March 1 and March 31? There are several ways you could answer those questions, and it's not clear that one answer is "right".

If you want a simple appoximation, it's easy:

Otherwise you probably need to define precisely what a month is. Good luck.

Jaime M. Tovar
Ranch Hand
Posts: 133
If i remember, i used two calendars, one in the original date and one in the reference date. Then added while the original calendar was less (Date.before(Date)) than the reference date, have an integer variable holding how many cicles you have used. If not, add a month. Using the Calendar.add(). Hopes it helps.

Chris Beckey
Ranch Hand
Posts: 116
If you want the number of month boundaries crossed between dates you can use something like this:

BUT ... as was suggested earlier you may want to think about what "X months ago" really means.

Mohamed Nazeer
Greenhorn
Posts: 3

Thanks & Regards
Nazeer

Mohamed Nazeer
Greenhorn
Posts: 3

thank and regards
Nazeer

Campbell Ritchie
Sheriff
Posts: 50699
83
Welcome to the Ranch

Why are you using Vector as a List implementation? That is regarded as legacy code. All these substrings look very awkward.
And please fins the Code button; I have edited your post so you can see how much better it looks.

Mohamed Nazeer
Greenhorn
Posts: 3
Thanks ritchie from now i will post like that. Sorry if anything wrong in my post.

thanks and regards
Nazeer

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15568
46
Welcome to JavaRanch.

Please note that you're answering a post from December 2006, three and a half years ago. The original poster is most likely not still waiting for an answer...

Campbell Ritchie
Sheriff
Posts: 50699
83
Mohamed Nazeer wrote:. . . Sorry if anything wrong in my post.
There is now You have deleted all your code, so nobody understands the rest of the thread. Again: