在 Java 中查找两个日期范围之间的交集(以编程方式)

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

我想计算两个日期范围之间重叠的天数。从控制台读取 2 对日期范围,格式为:yyyy-mm-dd; 例如,如果两个日期是 2020-01-05 2020-03-31 和 2020-01-05 2020-03-20 该程序应该找到 2020-01-052020-03-20 之间的日期。但是,它不起作用。我想问一下我该如何解决这个问题?

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));
        }

    }

比那复杂一点(还不错)。

    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");
    }

此处代码的输出是:

75 days of overlap

我还使用了更好的变量名,并引入了对用户输入的时间间隔的验证。

我知道我应该在这里添加一些解释,但坦率地说,我发现使用 java.time 的代码本身就很清楚,我不知道需要解释什么。如果您想要包含开始日期和结束日期的天数,请记住将 ChronoUnit.DAYS.between() 中的 return 值加 1。请在评论中跟进,让我知道什么进一步的解释是合适的。