js is a simple instance of determining whether a set of dates is contiguous

  • 2021-07-02 23:06:21
  • OfStack

This is a question asked by a friend in the group. At that time, I said it was enough to judge whether day was adjacent. Later, after careful consideration, I found that it was completely wrong.

Problem demand

Given five dates in the same format, how can we judge whether they are five consecutive days?

At that time, I sorted after the first reaction getDay (), and then compared it before and after. .

But if you think about it carefully, it is totally wrong, for example, this week's 1 and next week's 2, which will also misjudge.

Moreover, it is not only such a problem, but also such problems as cross-month, cross-year and leap month.

Then you have the following code.

Let the timestamp be smoothed out by 1 cut

In order not to entangle these problems, I thought of timestamps, which can completely ignore the above problems, as long as the timestamps are processed and finally compared.

Then I gave the following code:


let days = [
 '2016-02-28',
 '2016-02-29', //  Leap month 
 '2016-03-01', //  Cross-moon 
 '2016-03-02',
 '2016-03-03',
]

//  Sort first, then turn to timestamp 
let _days = days.sort().map((d, i) => {
 let dt = new Date(d)
 dt.setDate(dt.getDate() + 4 - i) //  Process to the same date 

 return +dt
})

//  Compare whether timestamps 1 To 
console.log(
 _days[0] == _days[1] &&
 _days[0] == _days[2] &&
 _days[0] == _days[3] &&
 _days[0] == _days[4]
)

All the problems of ok 1 have been solved, and it doesn't matter whether it is a new year, a month or a leap month.

Universal function encapsulation

The above code is still a little flawed, because the minutes and seconds are not processed, and if sometimes the minutes and seconds are erased first.


let days = [
 '2016-02-28 12:00:00',
 '2016-02-29 12:00:01', //  Leap month 
 '2016-03-01 12:00:02', //  Cross-moon 
 '2016-03-02 12:00:03',
 '2016-03-03 12:00:04',
 '2016-03-04 12:00:04',
]

console.log(continueDays(days))

function continueDays(arr_days) {
 //  Sort first, then turn to timestamp 
 let days = arr_days.sort().map((d, i) => {
  let dt = new Date(d)
  dt.setDate(dt.getDate() + 4 - i) //  Process to the same date 

  //  Erase   Hour   Points   Seconds   Milliseconds 
  dt.setHours(0)
  dt.setMinutes(0)
  dt.setSeconds(0)
  dt.setMilliseconds(0)

  return +dt
 })

 let ret = true

 days.forEach(d => {
  if (days[0] !== d) {
   ret = false
  }
 })

 return ret
}

This function only changed 2 places, erase time, second, millisecond and loop comparison, and everything else is 1.

Summary

js processing time is very simple, such as writing a date plug-in. In fact, it is very easy to realize with Date, but you need to know api of Date.

Of course, to say simple, or php is the simplest, which is simply against the sky.


Related articles: