Home > database >  difference between two dates in year month day
difference between two dates in year month day

Time:10-01

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, 5 month,23 day

CodePudding user response:

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

CodePudding user response:

Use Duration.between() - all you need to do is to convert your java.util.Date into suitable Temporal. Here is an example:

Date startDate = "24/05/2020;
Date endDate = "21/09/2021";
Duration d = Duration.between(startDate.toInstant(), endDate.toInstant());
System.out.println(d.getSeconds());
  • Related