DOMINIK SYMONOWICZ's blogs - FOREVER HUNGRY of knowledge, sarcasm, smiling, music, dancing, and food ...lots of food.
This blog is as notes with solutions for simple problems that happen to a developer. A non-it blog can be found here: Dominik Symonowicz's non-IT blog and website
I tried to give a simplified solution with an explanation, added documentation, sarcastic comment and weird example.
I hope you will enjoying reading.

18 August 2016

How to get difference between 2 dates ( LocalDate ) in years , months or days ?

Solution for :
Java 8 and above

STORY:

August in my month of Java 8 where I try practice various things that are new in Java 8 and I should know already. At some point , I tried to create person with birthday stored as LocalDate and get age in years , but I found it that there is no method on Duration to check that. I was wonder can I do it this using only Java 8 . As it turns out yes.

SOLUTION:
You need use ChronoUnit class that has a nice method to do this.LocalDate birthday = LocalDate.of(1980,4,4);ChronoUnit.YEARS.between(birthday,LocalDate.now()));

EXAMPLE: (To run this example you need copy these 2 classes and add junit and assertJ libraries )