java.time
Quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API:
- Use
Period#between
to get the period between two LocalDate
s.
- Note that the month name in your string is in lowercase and therefore, you will need to build the
DateTimeFormatter
using parseCaseInsensitive
function.
- Never use
DateTimeFormatter
without a Locale
.
Demo:
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("d MMMM uuuu")
.toFormatter(Locale.ENGLISH);
LocalDate since = LocalDate.parse("17 april 2010", dtf);
LocalDate now = LocalDate.parse("15 april 2011", dtf);
Period period = Period.between(since, now);
String strPeriod = String.format("%d years %d months %d days", period.getYears(), period.getMonths(),
period.getDays());
System.out.println(strPeriod);
}
}
Output:
0 years 11 months 29 days
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.