Home > Blockchain >  Create an array with time intervals and add 2 hours
Create an array with time intervals and add 2 hours

Time:01-20

I need to create an array of elements in javascript, which add 2 hours to a certain time I set. I give an example. The time is

14:00.

I need, to create an array that contains all 30 minute intervals up to 16:00.
Ex

14:00
14:30
15:00
15:30

CodePudding user response:

What I would do was to create two methods: addTime and createDateArray.

On addTime function we use to convert a timestamp into a Date object so it is easier for you to manage rather than an 14:00 string.

const addTime = (_dateTimestamp, addHours, addMinutes, addSeconds) => { 
 const date = new Date();
 date.setTime( _dateTimestamp );
 
 const newDate = new Date();
 if(addHours) newDate.setHours( date.getHours()   addHours );
 if(addMinutes) newDate.setMinutes( date.getMinutes()   addMinutes );
 if(addSeconds) newDate.setSeconds( date.getSeconds()   addSeconds );
 
 return newDate;
}

const createDateArray = (date, minuteInterval, amount) => { 
  let array = [];
  for(let i = 1; i <= amount; i  ) {
    const time = addTime( date, 0, minuteInterval * i, 0);
    array.push( time );
  }
  return array;
}

const dateToIncrement = new Date().getTime();
const minutesInterval = 30; // every 30 minutes
const amountTimes = 10; // will run through 10 times, so it'll calculate the minutes 10 times

const result = createDateArray( dateToIncrement, minutesInterval, amountTimes );

console.log(result);

You can also use the addTime function for other properties like hours and seconds if you wish by setting the second and last argument of the method.

I hope the code above makes sense and you can make use of it.

CodePudding user response:

Here is a function that produces the time specifications as strings. It can take an optional second argument to specify the end-time (16:00 in your question).

Two utility functions convert a time string to (and from) a number of minutes.

Finally, the result array is created with Array.from:

const toMinutes = str => str.split(":").reduce((h, m) => h * 60    m);

const toString = min => (Math.floor(min / 60)   ":"   (min % 60))
                       .replace(/\b\d\b/, "0$&");

function slots(startStr, endStr="16:00") {
    let start = toMinutes(startStr); 
    let end = toMinutes(endStr);
    return Array.from({length: Math.floor((end - start) / 30)   1}, (_, i) =>
        toString(start   i * 30)
    );
}

console.log(slots("14:00"));

CodePudding user response:

You can create a basic function like this :

   function getTimes(start) {
    start = parseInt(start) * 2   ( start.slice(-2) > 0);
    end = start 60/12;
    return Array.from({length: end - start}, (_, i) =>
        (((i   start) >> 1)   ":"   ((i   start)%2*3)   "0").replace(/^\d:/, "0$&"));
};

And use with :

getTimes("14:00");
  •  Tags:  
  • Related