How to get the time points associated with multiple time periods in javascript
滿天的星座
滿天的星座 2017-05-19 10:31:10
0
1
609

Assume that there are the following time periods

00:00 - 03:00
03:00 - 03:30
01:00 - 03:20
12:30 - 14:00
13:36 - 15:00

At this time, 03:00 is a time point, because 03:00 is included in each time period, 14:00 or 13:36 is a point in time

So, how to obtain this associated node in multiple time periods? All it takes is one time node.

Or how do I group these time periods

[
00:00 - 03:00
03:00 - 03:30
01:00 - 03:20
]

[
12:30 - 14:00
13:36 - 15:00
]

滿天的星座
滿天的星座

reply all(1)
習慣沉默

Just group the times in the same interval into one group. It’s very simple. Just sort them first, and then find the time that starts later than the end of the previous time period.

Assume that time is stored in Number format (the number of milliseconds from 1 January 1970 00:00:00 UTC)

Time period structure:

{
  start: 1493125454502,
  end: 1493125454516
}
function sortTime (times) {
  if (times.length <= 1) { return times }

  times = times.sort((a, b) => a.start !== b.start ? a.start - b.start : a.end - b.end)

  let result = []
  let beginIndex = 0

  for (let i = 1; i < times.length; i += 1) {
    if (times[i].start > times[i - 1].end) {
      result.push(times.slice(beginIndex, i))
      beginIndex = i
    }
  }

  if (beginIndex !== times.length) {
    result.push(times.slice(beginIndex, times.length))
  }

  return result
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template