Home > Back-end >  I want to add 15 minutes slot to each StartTime in a loop and store in array of objects
I want to add 15 minutes slot to each StartTime in a loop and store in array of objects

Time:05-25

 const createTimeSlots=(fromTime,toTime)=>{
        let timeAndDate=new Date()
        let timeDates=
        let array=[];
        let ob={}
        while(timeAndDate<=timeDates){
            ob={
                StartTime:timeAndDate.add(15,'minutes'),
                EndTime:timeDates
            }
            array.push(ob);
           
        }
        return array
}

I want to add 15 minutes slot to each StartTime in a loop and store in array of objects. timeAndDate=StartTime and timeDates=endTime for example 25th may 2:00pm is starttime and endTime is 25thmay 3pm so i want to add 15 minutes to each start time timestamp till it reaches 3pm

CodePudding user response:

Assuming the inputs are in timestamp, add 15 mins equivalent of timestamps and push that timestamp(or push mins/hrs etc.). Here's the code example where start time is current timestamp and endtime is current 3hrs in timestamp.

   function createSlots(start, end) {
    let slots = [];
    const mins = 15 * 60 * 1000; // 15 mins

    const date = (dt) => new Date(dt);

    while (start <= end) {
        start  = mins;

        // only mins
        //slots.push(date(start).getMinutes());

        // hrs    mins
        slots.push(`${date(start).getHours()}:${date(start).getMinutes()}`);
    }
    return slots;
}

var slots = createSlots(Date.now(), Date.now()   3 * 3600 * 1000); // from (now) to (now   3hrs)
console.log("slots : ", slots);

CodePudding user response:

Let's assume inputs are valid date-time format. This solution will work across dates, let's say you give the start time today and end time tomorrow then also it will work without any issue.

const createTimeSlots = (fromTime, toTime, slotLength =15*60) => {
    let slotStart = new Date(fromTime).valueOf();
    let slotEnd = new Date(fromTime).valueOf()   slotLength * 1000;
    let endEpoch = new Date(toTime).valueOf();
    let ob = [];
    for (slotEnd; slotEnd <= endEpoch; slotEnd = slotEnd   slotLength * 1000) {
        ob.push({
            'from': formatDate(slotStart),
            'to': formatDate(slotEnd)
        });
        slotStart = slotEnd;
    }
    return ob;
}

function formatDate(epoch) {
    let d = new Date(epoch);
    let month = String((d.getMonth()   1)).padStart(2, '0');
    let day = String((d.getDate())).padStart(2, '0');
    let hours = String((d.getHours())).padStart(2, '0');
    let mins = String((d.getMinutes())).padStart(2, '0');

    return `${d.getFullYear()}-${month}-${day} ${hours}:${mins}`;
}

const from = "2022-05-25 23:00";
const to = "2022-05-26 01:00";
const slotLength = 15 * 60; //seconds
var r = createTimeSlots(from, to, slotLength );
console.log(r);

  • Related