javadatetimerangechronounit

Finding the intersection between two date ranges in Java (programatically)


I would like to calculate the number of the overlapping days between two date ranges. The 2 pairs of date ranges are read from the console in the format: yyyy-mm-dd; For example, if the two dates are 2020-01-05 2020-03-31 and 2020-01-05 2020-03-20 the program should find the days between 2020-01-05 and 2020-03-20. However, it doesn't work. I would like to ask how can I fix this?

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;

    public class Dates {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String a  = sc.nextLine();
            String b = sc.nextLine();
            String c  = sc.nextLine();
            String d = sc.nextLine();
            LocalDate ldt1 = LocalDate.parse(a);
            LocalDate ldt2 = LocalDate.parse(b);
            LocalDate ldt3 = LocalDate.parse(c);
            LocalDate ldt4 = LocalDate.parse(d);
            System.out.println(ChronoUnit.DAYS.between(ldt1,ldt2,ldt3,ldt4));
        }

    }

Solution

  • It’s a little more complicated than that (not badly).

        String i1StartStr = "2020-01-05";
        String i1EndStr = "2020-03-31";
        String i2StartStr = "2020-01-05";
        String i2EndStr = "2020-03-20";
        LocalDate i1Start = LocalDate.parse(i1StartStr);
        LocalDate i1End = LocalDate.parse(i1EndStr);
        LocalDate i2Start = LocalDate.parse(i2StartStr);
        LocalDate i2End = LocalDate.parse(i2EndStr);
        
        if (i1End.isBefore(i1Start) || i2End.isBefore(i2Start)) {
            System.out.println("Not proper intervals");
        } else {
            long numberOfOverlappingDates;
            if (i1End.isBefore(i2Start) || i2End.isBefore(i1Start)) {
                // no overlap
                numberOfOverlappingDates = 0;
            } else {
                LocalDate laterStart = Collections.max(Arrays.asList(i1Start, i2Start));
                LocalDate earlierEnd = Collections.min(Arrays.asList(i1End, i2End));
                numberOfOverlappingDates = ChronoUnit.DAYS.between(laterStart, earlierEnd);
            }
            System.out.println("" + numberOfOverlappingDates + " days of overlap");
        }
    

    Output from the code as it stands here is:

    75 days of overlap

    I have also used better variable names. I believe the code is about self-explanatory now. I have introduced validation of the intervals that the user inputs.

    If you want the number of days inclusive of both start and end dates, remember to add 1 to the return value from ChronoUnit.DAYS.between().