Java. Calculating the elapsed years, months, and days between two dates

Good afternoon. Date intervals are given, for example: 28.01.2009 - 05.03.2013. The task is to calculate the exact number of full years, months and days in this period. Can you tell me how to do this?

Just the number of days I find so

    Date startDate = new SimpleDateFormat("dd.MM.yyyy").parse(s1);
    Date endDate = new SimpleDateFormat("dd.MM.yyyy").parse(s2);

    Calendar calendarStart = Calendar.getInstance();
    calendarStart.setTimeInMillis(startDate.getTime());

    Calendar calendarEnd = Calendar.getInstance();
    calendarEnd.setTimeInMillis(endDate.getTime());

    long difference = calendarEnd.getTimeInMillis() - calendarStart.getTimeInMillis();
    long days = difference /(24* 60 * 60 * 1000);

    System.out.println(days);

The result should be presented as: Years: 7, Months: 5, Days: 10

Author: R1zen, 2018-04-04

2 answers

Everything is quite simple using the java.time.* package classes (in Java 8 and later):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
LocalDate startDate = LocalDate.parse("28.01.2009", formatter);
LocalDate endDate = LocalDate.parse("05.03.2013", formatter);
Period period = Period.between(startDate, endDate);
System.out.println(period.getYears());      // 4
System.out.println(period.getMonths());     // 1
System.out.println(period.getDays());       // 5
 11
Author: Alex Chermenin, 2018-04-04 09:05:16