Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

320
Visualizações
Get array of strings based on a time interval

I have two datetimes, e.g.:

"start": "2021-04-10T10:05:00+02:00"
"end": "2021-04-10T11:35:00+02:00"

What I would like to get out from this is an array of strings based on the duration between the two dates, in e.g. a quarter interval. So basically the above should result in:

var timeArray = ["10:00", "10:15", "10:30", "10:45", "11:00", "11:15", "11:30"]

I know I can get the time duration between dates from the intervalToDuration function in the date-fns package, but I am not sure how to create these timestamps from that.

Any ideas ?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

function getTimeArray(int, d1, d2){

  let d1_ = new Date(d1);
  let d2_ = new Date(d2);

  let min = d1_.getMinutes();
  let m = (min>=0&&min<=14)?0:(min>14&&min<=29)?15:(min>29&&min<=44)?30:(min>44&&min<=59)?45:0;
  d1_.setMinutes(m);
  let arr = [];

  do {
    let gh = ("0"+d1_.getHours()).slice(-2);
    let gm = ("0"+d1_.getMinutes()).slice(-2);
    arr.push(`${gh}:${gm}`);

    d1_.setMinutes(d1_.getMinutes()+int);
    
  } while (d1_ <= d2_);

  return arr;
}

let arr = getTimeArray(15, "2021-04-10T10:05:00+02:00", "2021-04-10T11:35:00+02:00");

console.log(arr);

about 4 years ago · Juan Pablo Isaza Relatório

0

I would break it down like this, then iterate from start to end time, pushing each quarter hour into the array.

var start = "2021-04-10T10:05:00+02:00"
start = start.split("T")[1].split("+")[0]
startHour = start.split(":")[0]
startMin = start.split(":")[1]


var end = "2021-04-10T11:35:00+02:00"
end = end.split("T")[1].split("+")[0]
endHour = end.split(":")[0]
endMin = end.split(":")[1]
about 4 years ago · Juan Pablo Isaza Relatório

0

Recently I came across the same case and got the following solution.

Let's play with the time rather than the DateTime.

timeslot will be the main function and it takes three arguments timeInterval, startTime and endTime.

timeInterval => in minutes
startTime => min 00:00 and max 24:00
endTime => min 00:00 and max 24:00


const timeslots = (timeInterval, startTime, endTime) => {
    // get the total minutes between the start and end times.
    var totalMins = subtractTimes(startTime, endTime);

    // set the initial timeSlots array to just the start time
    var timeSlots = [startTime];

    // get the rest of the time slots.
    return getTimeSlots(timeInterval, totalMins, timeSlots);
}

// Generate an array of timeSlots based on timeInterval and totalMins

const getTimeSlots = (timeInterval, totalMins, timeSlots) => {
    // base case - there are still more minutes
    if (totalMins - timeInterval >= 0) {
        // get the previous time slot to add interval to
        var prevTimeSlot = timeSlots[timeSlots.length - 1];
        // add timeInterval to previousTimeSlot to get nextTimeSlot
        var nextTimeSlot = addMinsToTime(timeInterval, prevTimeSlot);
        timeSlots.push(nextTimeSlot);

        // update totalMins
        totalMins -= timeInterval;

        // get next time slot
        return getTimeSlots(timeInterval, totalMins, timeSlots);
    } else {
        // all done!
        return timeSlots;
    }
}

// Returns the total minutes between 2 time slots

const subtractTimes = (t2, t1) => {
    // get each time's hour and min values
    var [t1Hrs, t1Mins] = getHoursAndMinsFromTime(t1);
    var [t2Hrs, t2Mins] = getHoursAndMinsFromTime(t2);

    // time arithmetic (subtraction)
    if (t1Mins < t2Mins) {
        t1Hrs--;
        t1Mins += 60;
    }
    var mins = t1Mins - t2Mins;
    var hrs = t1Hrs - t2Hrs;

    // this handles scenarios where the startTime > endTime
    if (hrs < 0) {
        hrs += 24;
    }

    return (hrs * 60) + mins;
}

// Gets the hours and minutes as intergers from a time string

const getHoursAndMinsFromTime = (time) => {
    return time.split(':').map(function (str) {
        return parseInt(str);
    });
}

// Adds minutes to a time slot.

const addMinsToTime = (mins, time) => {
    // get the times hour and min value
    var [timeHrs, timeMins] = getHoursAndMinsFromTime(time);

    // time arithmetic (addition)
    if (timeMins + mins >= 60) {
        var addedHrs = parseInt((timeMins + mins) / 60);
        timeMins = (timeMins + mins) % 60
        if (timeHrs + addedHrs > 23) {
            timeHrs = (timeHrs + addedHrs) % 24;
        } else {
            timeHrs += addedHrs;
        }
    } else {
        timeMins += mins;
    }

    // make sure the time slots are padded correctly
    return String("00" + timeHrs).slice(-2) + ":" + String("00" + timeMins).slice(-2);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda