File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Getting months from date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Getting months from date" Watch "Getting months from date" New topic

Getting months from date

Neeba Rebbaca
Ranch Hand

Joined: Oct 21, 2008
Posts: 159
I want to know how to get total number of months between given dates.
Please ,help me..
Vijitha Kumara

Joined: Mar 24, 2008
Posts: 3902

I'll give you a hint Try using API for Calendar and Date. You can start there.
[ October 22, 2008: Message edited by: Vijitha Kumara ]

[How to ask questions] [Twitter]
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10836

Hi Neeba Rebbaca ,
Welcome to the Ranch. We are happy to have you here

We encourage everybody to try out things on their own because that is the best way to learn things.

Check out this link. It will give you more information on how to extract the most of the ranch members.

So why don't you tell us what you have tried out so far and we can take it up from there?
Which part are you stuck at? The approach to solve this problem? The logic? The code?

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Neeba Rebbaca
Ranch Hand

Joined: Oct 21, 2008
Posts: 159
i tried in this way:

This works well if both the dates fall within a year.If between different year.
kranthi chamarthi
Ranch Hand

Joined: May 08, 2007
Posts: 95
You can do it using API. But i feel that it will be easy applying your own logic. For example
parse the given dates and get the startyear,endyear,startmonth,endmonth.
months=(years-2)*12; //since start year and end year are not completely included
months=months+(endmonth-1)+(12-startmonth);//since start month and end months are not completely inlcuded.
Correct me if i am wrong
Romit Bose
Ranch Hand

Joined: Oct 03, 2007
Posts: 50
I agree with the fact that using logic to solve this will be very helpful in developing the programming skills. However, in case you want to try your hands on APIs, then the class java.util.GregorianCalendar will be helpful. refer to the Javadoc and you will know how to use them.

[ October 24, 2008: Message edited by: Romit Bose ]
Rob Spoor

Joined: Oct 27, 2005
Posts: 20279

Don't use Date.getMonth - it's deprecated and should not be used. It advices you to use Calendar.get(Calendar.MONTH) instead.

Given a Date object you can create a Calendar object quite easily:

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Getting months from date
It's not a secret anymore!