This is a question asked by a friend in the group. At that time, I said that I could just judge whether the day was adjacent. Later, I thought about it carefully and found that it was completely wrong.
Problem requirements
Given 5 dates of the same format, how do you determine whether it is 5 consecutive days?
My first reaction was to getDay() and sort it, and then compare it before and after. .
But if you think about it carefully, it is completely wrong. For example, this will also be misjudgment.
And it is not just such a problem, but also crossing the month, New Year's Eve, leap month and other issues.
Then there is the following code.
Let the timestamp smooth everything
In order not to worry about these issues, I thought of timestamps, and this guy can completely ignore the above problems. Just process the timestamp and compare them in the end.
Then I gave the following code:
let days = [ '2016-02-28', '2016-02-29', // Leap month'2016-03-01', // Cross month'2016-03-02', '2016-03-03',]// Sort first, then turn the timestamp let _days = days.sort().map((d, i) => { let dt = new Date(d) dt.setDate(dt.getDate() + 4 - i) // Processed as the same date return +dt})// Compare whether the timestamps are the same console.log( _days[0] == _days[1] && _days[0] == _days[2] && _days[0] == _days[3] && _days[0] == _days[4])OK All problems have been solved, and it doesn’t matter if you cross the New Year, cross the month, or leap month.
General Function Encapsulation
The above code is still a bit flawed, because the time, minute and second are not processed, and if there are times, minute and second, you must also erase it first.
let days = [ '2016-02-28 12:00:00', '2016-02-29 12:00:01', // Leap month'2016-03-01 12:00:02', // Cross-month'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 the timestamp let days = arr_days.sort().map((d, i) => { let dt = new Date(d) dt.setDate(dt.getDate() + 4 - i) // Processed as the same date // Erased hours, minutes, seconds, milliseconds, 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 is just changed in 2 places, erasing time, minute, second, millisecond and loop comparison, and the others are the same.
summary
The processing time of js is still very simple. For example, writing a date plug-in is actually very easy to implement with the help of Date, but you need to understand the Date API.
Of course, to say that it is simple, or php is the simplest, that is simply amazing.
The above simple example of judging whether a set of dates is continuous is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.