背景
分配工作任务、或者项目申报中,日期相关的一般会有开始时间(startTime),结束时间(endTime)。
有时候需要确认两条数据的时间跨度是否有重叠。
import java.time.LocalDate; public class TestDuration { public static void main(String[] args) { String startTime = "2020-04-13"; String endTime = "2020-07-20"; String [] testCase = new String[] { "2020-04-13","2020-07-20", "2020-04-12","2020-07-20", "2020-04-12","2020-07-19", "2020-04-13","2020-07-20", "2020-07-20","2020-07-25", "2020-07-19","2020-07-25", "2020-01-12","2020-04-13", "2020-04-13","2020-04-13", //不重复 "2020-07-21","2020-07-21", "2020-07-21","2020-07-25", "2020-01-01","2020-04-12" }; for (int i = 0; i < testCase.length; i+=2) { boolean matched = match(startTime, endTime, testCase[i], testCase[i + 1]); System.out.println("重复申报:"+matched); } } static boolean match(String projectStartTime1, String projectEndTime1,String projectStartTime2,String projectEndTime2) { LocalDate startTime1 = formatDate(projectStartTime1); LocalDate endTime1 = formatDate(projectEndTime1); LocalDate startTime2 =formatDate(projectStartTime2); LocalDate endTime2 = formatDate(projectEndTime2); return !(startTime2.isAfter(endTime1)||startTime1.isAfter(endTime2)); } }
public static LocalDate formatDate(String date) { return LocalDate.parse(date); }
public boolean checkDuplicateApply(Project project) { Date startTime = project.getProjectStartTime(); Date endTime = project.getProjectEndTime(); List<Project> projects = projectMapper.queryList(Collections.singletonMap("projectName",project.getProjectName())); for (Project thisProject : projects) { if(match(startTime,endTime,thisProject.getProjectStartTime(),thisProject.getProjectEndTime())) { return false; } } return true; } private static boolean match(Date projectStartTime1, Date projectEndTime1,Date projectStartTime2,Date projectEndTime2) { return !(projectStartTime2.after(projectEndTime1)||projectStartTime1.after(projectEndTime2)); }