JavaScript function to find time between ranges for each trip

I hope your day is going well and having no code issues ! For my case I do and I need help.

I am facing a challenge as follow: So I have 3 time ranges

  1. The first one from 2.00AM until 4.00PM (> 2AM && <= 04 PM)
  2. The second time range is from : 4.00PM until 8.00PM (> 4PM && <= 8 PM)
  3. The third time range is from : 8.00PM until 2.00AM (> 8PM && <= 02AM)

I have also a driver that is allowed to do trips. A Trip is known with both properties: timeStart(timestamp) and timeEnd(timestamp)

I want to know how long does it take for a certain trip to last between the time ranges I mentioned above! Also, I want the result to be in minutes.

For instance:

  • timeStart : 1618905600000 // Tuesday , April 20,2021 08:00:00AM
  • timeEnd : 1618920000000 // Tuesday , April 20,2021 12:00:00PM

The result for each range should be :

  • Range1(2AM-4PM) : 4 hours(240 minutes )
  • Range2(4PM-8PM) : 0 minutes
  • Range3(8PM-2AM) : 0 minutes

Note: A trip can last longer than 24 hours/day.

Technologies : JavaScript, Node.js, TypeScript.