Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting months from date

 
Neeba Rebbaca
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to know how to get total number of months between given dates.
Please ,help me..
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 11027
12
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch

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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20526
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic