• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calculate number of months between two dates  RSS feed

 
Ranch Hand
Posts: 208
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose someone's birth date is 8/29/2016. How can I create a method that calculates the number of full months between 8/29/2016 and today's date which is 8/20/2017? For this example, the method should return 11 months since 8/29/2017 is in the future.
 
Bartender
Posts: 2155
46
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ChronoUnit.DAYS.betweenChronoUnit.MONTHS.between will help you.

For some reason I read that you want a number of days.
 
Fred Victa
Ranch Hand
Posts: 208
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Paweł Baczyński wrote:ChronoUnit.DAYS.betweenChronoUnit.MONTHS.between will help you.

For some reason I read that you want a number of days.



I'm sorry. I meant calculate a person's age in terms of the number of months. For example, if someone was born on 8/21/2015 and today's date is 8/21/2017, then he is 24 months old.
 
lowercase baba
Bartender
Posts: 12613
50
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first step is to write out how YOU would calculate it by hand.  An example is always nice, but it isn't a spec or an algorithm. 

So if I were born on Jan 2, 1975, how would you calculate my age in months?
 
Marshal
Posts: 5593
384
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without thinking about very clever ways (if there are such), have look at the LocalDate class. Task supposed to be quite simple.
 
Fred Victa
Ranch Hand
Posts: 208
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came up with a solution. Here it is:


 
Marshal
Posts: 58456
178
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use Calendar. A dreadful class to use. Use LocalDate←link. You can read about the new date classes in the Java™ Tutorials.
 
Ranch Hand
Posts: 1537
11
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Don't use Calendar. A dreadful class to use. Use LocalDate←link. You can read about the new date classes in the Java™ Tutorials.



Agreed!

The java 8 LocalDate API is amazing. Check out all the examples online.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!