Removing a timeframe from another timeframe

Viewed 42

I have a case-scenario which I don't really know how to handle. I have two arrays of objects that contain date/time ranges. What I need to do is check if range from the first set, is contain in the rage of the second set, and if it is remove it. For example:

abc:[
   {
      "start": "2021-11-25 16:30:00",
      "end": "2021-11-25 17:30:00"
   }
]

xyz:[
   {
      "start": "2021-11-25 09:00:00",
      "end": "2021-11-25 18:00:00"
   },
   {
      "start": "2021-11-26 15:00:00",
      "end": "2021-11-26 19:00:00"
   }
]

I need to remove the range of abc from xyz, so in the end the xyz would look like so:

xyz:[
   {
      "start": "2021-11-25 09:00:00",
      "end": "2021-11-25 16:30:00"
   },
   {
      "start": "2021-11-25 17:30:00",
      "end": "2021-11-25 18:00:00"
   },
   {
      "start": "2021-11-26 15:00:00",
      "end": "2021-11-26 19:00:00"
   }
]

this can be done either in PHP or JS.

Google so far was not very hepfull.

Thanks in advance for any kind of help

1 Answers

eheh the day that google will be able to solve algorithms all software developers disapear. here's some fast javascript:

        
var abc=[
   {
      "start": "2021-11-25 16:30:00",
      "end": "2021-11-25 17:30:00"
   }
]

var xyz =[
   {
      "start": "2021-11-25 09:00:00",
      "end": "2021-11-25 18:00:00"
   },
   {
      "start": "2021-11-26 15:00:00",
      "end": "2021-11-26 19:00:00"
   }
];

var newXyz=[];
for(var i in xyz){
  var start = new Date(xyz[i]["start"]).getTime();
  var end = new Date(xyz[i]["end"]).getTime();
  var collisionDetected=false;
  for(var j in abc){
    var start2 = new Date(abc[j]["start"]).getTime();
    var end2 = new Date(abc[j]["end"]).getTime();
    if(
      start2>start &&
      start2<end &&
      1
    ){
      newXyz.push({"start":xyz[i]["start"],"end":abc[j]["start"]});

      if(
        end2<end &&
        1
      ){
        newXyz.push({"start":abc[j]["end"],"end":xyz[i]["end"]});
      }
      collisionDetected=true;
      break;
    }
  }
  if(collisionDetected==false){
    newXyz.push({"start":xyz[i]["start"],"end":xyz[i]["end"]});
  }
}

xyz = newXyz;

console.dir(xyz);

Related