Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
Javascript create arrays of time pairs every half hour

i should generate an array of strings that maps time pairs to me every half hour, starting from a departure time like 1pm and an end time like 11pm, that i can dynamically create an array of this type:

return ['13: 00-13: 30 ',' 13: 30-14: 00 ',' 14: 00-14: 30 ',' 14: 30-15: 00 ',' 15: 00-15: 30 ', '20: 00-20: 30', '20: 30-21: 00', '21: 00-21: 30', '21: 30-22: 00', '22: 00-22: 30 '] 

I had found an approach but was unable to adapt it to my needs:

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

I get an output like this, which is not good:

[ '13:00',
  '13:30',
  '14:00',
  '14:30',
  '15:00',
  '15:30',
  '16:00',
  '16:30',
  '17:00',
  '17:30',
  '18:00',
  '18:30',
  '19:00',
  '19:30',
  '20:00',
  '20:30',
  '21:00',
  '21:30',
  '22:00',
  '22:30',
  '23:00',
  '23:30',
  '24:00' ]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I'd just track everything in minutes, with two helpers for conversion between strings and minutes:

function parseTime(timeString) {
  let time = timeString.split(":");
  return time[0] * 60 + time[1] * 1;
}

function timeString(time) {
  let h = Math.floor(time / 60);
  if (h > 23) h -= 24;
  let m = time % 60;
  return h.toString().padStart(2, "0") + ":" + m.toString().padStart(2, "0");
}

function getTimes(start, end) {
  start = parseTime(start);
  end = parseTime(end);
  if (end < start) end += 24 * 60;
  let result = [];
  while (start < end) {
    result.push(timeString(start) + "-" + timeString(start + 30));
    start += 30;
  }
  return result;
}
console.log(getTimes("13:00", "24:00"));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!