简体   繁体   中英

Find date ranges from a collection of dates Javascript

I know this is similar to this Question , but I need different results and in JavaScript.

I have an string of dates like this, that may not be in order. 03/27/2017,03/28/2017,03/29/2017,04/04/2017,04/05/2017,04/06/2017,04/12/2017,04/13/2017,04/14/2017, 05/02/2017

Date format is mm/dd/yyyy

I need to split this into an array of dates, which I can do. But then I need to loop through all dates and if the dates are connected then it needs to be a date range. If there is a single date, then it would be a single date range.

So I would need these results from the above dates.

[
    {'start': 03/27/2017, 'end': 03/29/2017 }, 
    {'start': 04/04/2017, 'end': 04/06/2017}, 
    {'start': 04/12/2017, 'end': 04/14/2017 }, 
    {'start': 05/02/2017, 'end': 05/02/2017}
]

I am doing this app in JavaScript, Typescript, lodash, angular 1.6.

Any help is greatly appreciated.

EDIT

I have a popup calendar that the user can select multiple dates. If the dates are consecutive then that is the date range, if it is a single date then that alone will be the date range. This is needed for the user to select their desired dates off, then these will be inserted into the DB.

Here is how I did it . I converted them to dates, and then did a math calculation to see if the next date was bigger than a day or not. If it was, then I stopped the current date range and started the next one.

let string = '03/27/2017,03/28/2017,03/29/2017,04/04/2017,04/05/2017,04/06/2017,04/12/2017,04/13/2017,04/14/2017, 05/02/2017';
  //split them and pull out any white spaces from beginning and end
  let dates = string.split(',').map(s=>{
    s = s.trim();
    let nums = s.split('/');
    let d = new Date(nums[2], nums[0], nums[1]);
    return {date:d, string: s};
  });
  let currentStart = dates[0];
  let result = [];
  for(let i = 1; i < dates.length; i++){
    let {date, string} = dates[i];
    //If last date, add range
    if(i == dates.length -1){
      console.log("hello");
      result.push({start: currentStart.string ,end: string});
    } else {
      let prevDate = dates[i-1] || currentStart; //in case prevDate is undefined
      let nextDate = dates[i+1];
      let diff = nextDate.date.getTime() - date.getTime();
      if(diff > (24 * 60 * 60 * 1000)){
        result.push({start: currentStart.string ,end: string});
        currentStart = nextDate;
      }
    }
  }

  console.log(result, 'result');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM