JS to determine whether there is an intersection in multiple date time periods


JS to determine whether there is an intersection in multiple date time periods

Recently, when using the daterange of element to select multiple time periods, it is required that they can not have intersection, any two dates can not have intersection, and the critical point is not good. After looking for some information on the Internet, they are not very satisfied, so I implemented it by myself. The main idea is to generate a date array for each selected date range, and then use lodash to compare these numbers Whether the group has intersecting elements.

The packages / libraries used are: dayjs, lodash’s intersection.
Why not use momentjs? Because it’s too big. Dayjs is small and can almost realize the function of moment. As for the intersection, it is used to judge the intersection of multiple array arrays. Continue to look down! ~ ~

//In the following example, it is obvious that September 11, 2020 is an intersection
const date1 = ['2020-09-01','2020-09-11'];
const date2 = ['2020-09-11','2020-09-30'];

The following code to achieve it.

Collect the date selected by the user through El date picker, which is a range
<el-date-picker @change="selectSpecialDateRange(index)" v-model=" item.time "Type =" daterange "value format =" yyyy MM DD "range separator = to" start placeholder = start date "end placeholder = end date" > < / El date picker >
Import the corresponding package
 import dayjs from 'dayjs'
 import {intersection} from 'lodash'
//This is mainly the use of dayjs to do one thing,
//The date range is generated as an array,
//For example: ['2020-09-01 ','2020-09-03'] 
//=> ['2020-09-01','2020-09-02','2020-09-03']
    const timeRange = this.Datelist[index].time
    this.Datelist[index].dateArr = []
    let i=0
      const endTime = dayjs(timeRange[0]).add(i, "days").format("YYYY-MM-DD")
      //Same as last date, jump out of loop
      if(endTime == timeRange[1]){
    //The following is a comparison of each pair
    const userArr1 = this.Datelist.map(v=>v.dateArr)
    let flag = false 
    for(let i=0;i<index;i++){
        //Compare each time with the previously selected date range in pairs
      const res = intersection(userArr1[index],userArr1[i])
        flag = true;
      this.deleitem (index) // do a remove operation
      this.$ message.error ('the dates you selected overlap')
      return false;
The effect picture is as follows:

JS to determine whether there is an intersection in multiple date time periods

Recommended Today

Looking for frustration 1.0

I believe you have a basic understanding of trust in yesterday’s article. Today we will give a complete introduction to trust. Why choose rust It’s a language that gives everyone the ability to build reliable and efficient software. You can’t write unsafe code here (unsafe block is not in the scope of discussion). Most of […]