Iterate through a range of dates in NodeJS

前端 未结 5 1644
抹茶落季
抹茶落季 2020-12-23 11:48

I would like to iterate through a range of calender dates, each iteration is +1 day. I would use something built around JodaTime in Java - is there something similar in Node

5条回答
  •  粉色の甜心
    2020-12-23 11:56

    As much as there are many utilities for this, they might be cumbersome to integrate into a useful loop to check against data.

    This should do the trick. It might be overkill, but you could very easily make this more argument based.

    var moment = require('moment');
    var _ = require('lodash');
    
    function(collectionsWithDateValues){
      var slots = [];
      var hours = {
        start: 7,   // 7am
        end: 21,    // 9pm
        window: 2   // How long each item should be slotted for.
      };
      var rightNow  = moment().add(0, 'days').hours(hours.start).minute(0).second(0);
      var cutoff    = moment(rightNow).add(14,'days'); // Check the next 2 weeks.
      for( rightNow ; rightNow.isBefore(cutoff) ; rightNow.add(hours.window, 'hours') ){
        // Check if we're going beyond the daily cutoff, go to the next day
        if(rightNow.isAfter(moment(rightNow).hour(hours.end))){
          rightNow.add(1, 'days').hour(hours.start);
        }
        var foundClash = false;
        _.forEach(collectionsWithDateValues,  function(item){
          // Check if the item is within now and the slotted time 
          foundClash = moment(item.date).isBetween(rightNow, moment(rightNow).add(hours.window, 'hours').subtract(1, 'minutes').seconds(59));
        });
    
        if(!foundClash){
          slots.push(rightNow.toString());
        }
      }
      return slots;
    }
    

提交回复
热议问题