ChrisJ
ChrisJ

Reputation: 225

Get the next possible day and hour given the current day

Im trying to write some logic so I can data-bind when the next occurrence will be out of a set of models based on the current date and time

sample data would be as follows. Days represents each day that is scheduled, hour is the hour it starts and enabled is self explanatory:

var collection = [{
    days: [0, 1, 2, 3, 4, 5, 6],
    hour: 8,
    enabled: true }, {
    days: [0, 1, 4, 5, 6],
    hour: 14,
    enabled: true }, {
    days: [0, 1, 2, 3, 4, 6],
    hour: 2,
    enabled: false }, {
    days: [0, 1, 2, 3, 4, 6],
    hour: 14,
    enabled: true }];

Here is a fiddle of my progress thus far: https://jsfiddle.net/5L5q01yk/2/ So far its checking through for anything schedules that happen today and then finding out of the possibilities the closest hour to the current. I need it to be the next occurrence whether its today or not.

Any help is appreciated

Upvotes: 0

Views: 100

Answers (1)

Dave
Dave

Reputation: 10924

I'd tackle this by mapping your initial inputs to an array of dates that represent the next available dates in your schedule, then it is simple to reduce this to the minimum of the results. You could really do this in one step, but the intermediate data structure might be useful to you so I've left it.

var collection = [{
    days: [0, 1, 2, 3, 4, 5, 6],
    hour: 8,
    enabled: true
}, {
    days: [0, 1, 4, 5, 6],
    hour: 14,
    enabled: true
}, {
    days: [0, 1, 2, 3, 4, 6],
    hour: 2,
    enabled: false
}, {
    days: [0, 1, 2, 3, 4, 6],
    hour: 14,
    enabled: true
}];

var nextTime = null;
var now = new Date();
var dayOfMonth = now.getDate();
var month = now.getMonth();
var dayOfWeek = now.getDay();
var year = now.getFullYear();
var hour = now.getHours();

var nextPossibleTimes = collection.map(function(daySchedule) {
  daySchedule.days = daySchedule.days.map(function(scheduledDay) {
    var dayOffset = scheduledDay - dayOfWeek;
    if ((scheduledDay < dayOfWeek) || (scheduledDay === dayOfWeek && daySchedule.hour < hour)) {
      //add a week
      dayOffset += 7;
    }
    return new Date(year, month, dayOfMonth + dayOffset, daySchedule.hour);
  });
  return daySchedule;
});

nextPossibleTimes.forEach(function(current) {
  current.days.forEach(function(date) {
    if (nextTime === null || nextTime > date)
      nextTime = date;
  });
});

var dateArr = nextTime.toString().split(" ");
var dateName = dateArr[0] + " " + dateArr[4];
  
console.log("Next available time: " + dateName);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Upvotes: 1

Related Questions