zoukankan      html  css  js  c++  java
  • 判断两个时间段是否重叠

    背景

    分配工作任务、或者项目申报中,日期相关的一般会有开始时间(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));
        }
  • 相关阅读:
    同步和异步Http请求工具类通过get和post方式发送请求
    c# IPC实现本机进程之间的通信
    C# 建立window服务
    WPF 将控件绑定到变量
    WPF触发器的使用
    C# DataTable 和List之间相互转换的方法
    WPF自适应窗体实现小结
    WPF简单导航框架(Window与Page互相调用)
    JavaEE框架面试题
    快速排序
  • 原文地址:https://www.cnblogs.com/passedbylove/p/14229128.html
Copyright © 2011-2022 走看看