Home > Software engineering >  split time data in Javascript vanilla
split time data in Javascript vanilla

Time:04-01

I'm trying to create a dynamic calendar. I have opening and closing hours.

I would like to make a loop to get all the half hour slots between these two times.

The goal is to create a div that contains the list of these schedules.

do you have a method, an idea please to help me achieve this?

My data, inside a json document, looks like this:

"minMax": {
                "min": "07:00",
                "max": "18:00"
            }

(I have already retrieved the day) my goal is to display the schedules.

const minHour = week[weekNumber].minMax.min // => 07:00
const maxHour = week[weekNumber].minMax.max // => 18:00

The problem is that I don't know how to split the schedules by half hour between the min hour and the max hour.

Thanks for your help and your time.

CodePudding user response:

Based on the information you gave I came up with this solution to generate half hour slots. If there is any corrections needed to be made or edge cases to handle, please let me know.

function halfHourSlots(min, max) {
  let slots = [];

  let [minHour] = min.split(':');
  let [maxHour] = max.split(':');

  minHour = Number(minHour);
  maxHour = Number(maxHour);

  while (minHour != maxHour) {
    let halfHourString = `${minHour}:30`.padStart(
      2,
      '0'
    );
    minHour  = 1;

    let hourString = `${
      minHour == 24 ? '00' : minHour
    }:00`.padStart(2, '0');

    slots.push(halfHourString);
    slots.push(hourString);
  }

  return slots;
}

console.log(halfHourSlots('07:00', '18:00'));

CodePudding user response:

You can try this,

var convertValue  = time => ((hour,min) => hour*2   min/30)(...time.split(':').map(parseFloat)),
    toTime = int => [Math.floor(int/2), int%2 ? '30' : '00'].join(':'),
    range  = (from, to) => Array(to-from 1).fill().map((_,i) => from   i),
    halfHourInterval = (t1, t2) => range(...[t1, t2].map(convertValue)).map(toTime);

console.log(halfHourInterval('07:00', '15:30'));
  • Related