const createTimeSlots=(fromTime,toTime)=>{Quiero agregar un espacio de 15 minutos a cada StartTime en un bucle y almacenarlo en una matriz de objetos.
Suponiendo que las entradas están en la marca de tiempo, agregue el equivalente de 15 minutos de las marcas de tiempo y presione esa marca de tiempo (o presione minutos/horas, etc.). Aquí está el ejemplo de código donde la hora de inicio es la marca de tiempo actual y la hora de finalización es actual + 3 horas en la marca de tiempo.
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);Supongamos que las entradas tienen un formato de fecha y hora válido. Esta solución funcionará en todas las fechas, digamos que usted da la hora de inicio hoy y la hora de finalización mañana, entonces también funcionará sin ningún problema.
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);