0

I have a two dates :

Date startDate = "24/05/2020;
Date endDate = "21/09/2021";

How to calculate difference in year/month/day

Example: 1 year, 3 month,27 day

  • What is a month (28 days, 29 days, 30 days, 31 days? Something else?)? And according to my calculator, May-24 to September-21 is not 5 months, but less than 4 months. – knittl Sep 30 '22 at 20:52
  • Can you have/convert dates to local date? – VaibS Sep 30 '22 at 21:02
  • I hope you can convert because doing date math without library support is hell, e.g. accounting for leap years, the ambiguity of month lengths (is Jan 31 to Feb 28 still a month? One day later each and they definitely are) and when you want hour precision or better you'll have fun with DST changes (which happen only in some countries and not on the same day for every country. Maybe the country even stopped doing that in the middle of your date period) and other fun things. – zapl Sep 30 '22 at 23:43

1 Answers1

1

You can use LocalDate#until to get the Period object from which you can further derive the days, months, years etc.

Demo:

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.ENGLISH);
        LocalDate startDate = LocalDate.parse("24/05/2020", formatter);
        LocalDate endDate = LocalDate.parse("21/09/2021", formatter);
        Period period = startDate.until(endDate);
        System.out.println(period);
        System.out.println(formatPeriod(period));
    }

    static String formatPeriod(Period period) {
        return String.format("%d years %d months %d days", period.getYears(), period.getMonths(), period.getDays());
    }
}

Output:

P1Y3M28D
1 years 3 months 28 days
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • DateTimeFormatter.ofPattern Call requires API level 26 (current min is 21) – Gegham Virabyan Oct 01 '22 at 19:22
  • @GeghamVirabyan - For any reason, if you have to stick to Java 6 or Java 7, you can use [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) 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](https://developer.android.com/studio/write/java8-support-table). Note that Android 8.0 Oreo already provides [support for `java.time`](https://developer.android.com/reference/java/time/package-summary). – Arvind Kumar Avinash Oct 01 '22 at 19:59
  • [This answer](https://stackoverflow.com/a/38922755/10819573) may be helpful to you in setting up ThreeTenBackport. – Arvind Kumar Avinash Oct 01 '22 at 20:01