Search code examples
javadatejava-timedurationlocaldate

Define the highest time unit of date difference that has a whole number


I have 2 dates:

LocalDate date1 = LocalDate.now().minusDays(40);
LocalDate date2 = LocalDate.now();

I want to figure out what is the biggest time unit I can pick to define the difference between the 2 (out of days, months, years), and to get its number. The perfect solution for me, I think, would been if Duration of java.time api had also toMonthsPart and toYearsPart as it has toDaysPart. This way I could do this:

Duration dif = Duration.between(date1, date2);

long daysPart = dif.toDaysPart();
if (daysPart > 0) {
    return ChronoUnit.DAYS.between(date1, date2);
}

long monthPart = dif.getMonthsPart();
if (monthPart > 0) {
    return ChronoUnit.MONTHS.between(date1, date2);
}

long yearPart = dif.getYearsPart();
if (yearPart > 0) {
    return ChronoUnit.YEARS.between(date1, date2);
}

throw new Exception("no difference");

But there is no such methods in the API. Is there another package can provide this functionality, or do you know of different approach to achieve my goal?


Solution

  • TL;DR

    Use Period instead of Duration.

    Demo:

    import java.time.LocalDate;
    import java.time.Period;
    
    class Main {
        public static void main(String[] args) {
            LocalDate today = LocalDate.now();
            LocalDate fortyDaysAgo = today.minusDays(40);
            Period period = Period.between(fortyDaysAgo, today);
            System.out.println(period);
            System.out.printf("%d year(s) %d month(s) %d day(s)%n", period.getYears(), period.getMonths(),
                    period.getDays());
        }
    }
    

    Output from a sample run:

    P1M9D
    0 year(s) 1 month(s) 9 day(s)
    

    ONLINE DEMO

    Learn more about the modern Date-Time API from Trail: Date Time.