Question:
Good afternoon. Date intervals are given, for example: 01/28/2009 – 03/05/2013. The task is to calculate the exact number of full years, months and days in this interval. Tell me how to do this?
I just find the number of days like this
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
Answer:
It's pretty straightforward using the classes in the java.time.*
Package (in Java 8 and newer):
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