# Getting months from date

Neeba Rebbaca
Ranch Hand
Posts: 162
I want to know how to get total number of months between given dates.

Vijitha Kumara
Bartender
Posts: 3913
9
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 ]

Maneesh Godbole
Saloon Keeper
Posts: 11064
13
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?

Neeba Rebbaca
Ranch Hand
Posts: 162
i tried in this way:

This works well if both the dates fall within a year.If between different year.

kranthi chamarthi
Ranch Hand
Posts: 95
Hi,
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.
Now
years=endyear-startyear;
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
Posts: 50
Hi!
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.

Thanks!
Romit
[ October 24, 2008: Message edited by: Romit Bose ]

Rob Spoor
Sheriff
Posts: 20546
56
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: