userimage

Find the difference between two dates using Java

I just want to find the difference between two dates but after visiting few sites now a kind of stuck and just thinking which one need to consider.

If anyone having the best solution then, please provide the source code or the code snippet of calculating the current date with some other date.

It would be find if any third party libraries using on your snippet because I just want a best and proper solution to find out the exact difference.

userimage

Here you can.

Please note if you are not using java 8 on your application then may go for Joda Time which is the alternate solution in your case.


import java.time.LocalDate;
import java.time.Period;

import org.joda.time.DateTime;
import org.joda.time.chrono.GregorianChronology;

public class DateDifference {
    public static void main(String[] args) {
        differenceBetweenDatesUsingJodaTime();
        System.out.println();
        differnceBetweenDatesUsingJava8();
    }

    public static void differenceBetweenDatesUsingJodaTime() {
        DateTime prevDate = new DateTime(2016, 4, 11, 0, 0, GregorianChronology.getInstance());
        DateTime currentDate = new DateTime();
        org.joda.time.Period diff = org.joda.time.Period.fieldDifference(prevDate.toLocalDate(),
                currentDate.toLocalDate());
        System.out.printf("JodaTime - Difference is %d years, %d months and %d days old", diff.getYears(), diff.getMonths(),
                diff.getDays());
    }

    public static void differnceBetweenDatesUsingJava8() {
        LocalDate prevDate = LocalDate.of(2016, 4, 11);
        LocalDate now = LocalDate.now();
        Period diff = Period.between(prevDate, now);
        System.out.printf("Java 8 - Difference is %d years, %d months and %d days old", diff.getYears(), diff.getMonths(),
                diff.getDays());
    }
}


Result :

JodaTime - Difference is 0 years, 7 months and 0 days old
Java 8 - Difference is 0 years, 7 months and 0 days old

Answer is