校验时间段是否与已有时间段存在交叉算法
生活随笔
收集整理的這篇文章主要介紹了
校验时间段是否与已有时间段存在交叉算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下面是算法示例:
//? 驗證時間有沒有交集 有交集返回失敗,注意,map集合中元素必須是偶數個k-v,
并且,當startTimeStr或endTimeStr等于其中一個日期時,可能算出來有誤,需要單獨情況考慮。
注:可以將入參的startTimeStr與endTimeStr、map的key與value全部拼接時分秒后,使用該算法,本人測試后沒有發現有錯誤的情況。
public static void main(String[] args) {String startTimeStr = "2021-04-02";String endTimeStr = "2021-04-11";Map<String,String> map = new HashMap<>();map.put("2021-04-01","2021-04-03");map.put("2021-04-04","2021-04-06"); // 7- 11map.put("2021-04-12","2021-04-14");map.put("2021-04-15","2021-04-17");map.put("2021-04-18","2021-04-20");map.put("2021-04-21","2021-04-23");log.info(">>>>>map:{}", JSON.toJSONString(map));// true表示有交叉,false表示無交叉Boolean checkFlag = null;// a. 判斷開始時間、結束時間是否包含臨近值;開始時間與結束時間一致時的處理Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();while (iterator.hasNext()){Map.Entry<String, String> next = iterator.next();String key = next.getKey();String value = next.getValue();if (startTimeStr.equals(key) || startTimeStr.equals(value)){checkFlag = true;break;}else if (endTimeStr.equals(key) || endTimeStr.equals(value)){checkFlag = true;break;}else if (startTimeStr.equals(endTimeStr)){DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");LocalDate startTime = LocalDate.parse(startTimeStr, df);LocalDate keyTime = LocalDate.parse(key, df);LocalDate valueTime = LocalDate.parse(value, df);if (startTime.isAfter(keyTime) && startTime.isBefore(valueTime)){checkFlag = true;break;}else {checkFlag = false;}}}log.info(">>>>>checkFlag:"+checkFlag);if (checkFlag != null){return checkFlag;}else {checkFlag = false;// b. 當指定開始時間、結束時間不包含map臨近時間,且 開始時間不等于結束時間,適用下面方法計算是否交叉List<Map<String,String>> timeList = new ArrayList<>();timeList.add(map);//創建map存所有時間SortedMap<String,Integer> hashMap = new TreeMap<>();int ii = 1;hashMap.put(startTimeStr, ii);hashMap.put(endTimeStr, ii);for (Map<String, String> map2 : timeList) {ii++;Set<Map.Entry<String,String>> entrySet = map2.entrySet();for (Map.Entry<String, String> entry : entrySet) {String value = entry.getValue();hashMap.put(value, ii);String key = entry.getKey();hashMap.put(key, ii);}}//存最后值List<Integer> arrayList = new ArrayList<>();Set<Map.Entry<String,Integer>> entrySet = hashMap.entrySet();for (Map.Entry<String, Integer> entry : entrySet) {Integer value = entry.getValue();arrayList.add(value);}//不相等則兩個時間有交集for (int j = 0; j < arrayList.size(); j++) {if ((j+1) >= arrayList.size()){checkFlag = false;log.info(">>>>>j+1 > arrayList.size()");break;}if(j%2==0){if(arrayList.get(j).intValue() != arrayList.get(j+1).intValue()){checkFlag = true;break;}}}}return checkFlag;}總結
以上是生活随笔為你收集整理的校验时间段是否与已有时间段存在交叉算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows服务器安全事件日志事件编号
- 下一篇: Matlab应变片仿真,应变片传感器的应