Search code examples
javascripttimeintervals

I want to be able to set different time intervals


I have these code that helps generate an array of times based on a start and an end time, it works well for 30 mins and less, but doesn't for 1 hour(60) and above...

export const getTimes = (start, end, timeInterval = 30) => {
  if (!start || !end) return
  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) * Number(timeInterval),
  ]).map(([h, m]) =>
    `${h % 12 || 12}:${m}${m.toString().length === 1 ? 0 : ""} ${
      "AP"[+(h > 11)]
    }M`.replace(/bdb/g, "0$&")
  )
}

console.log(getTimes("9:00", "22:00"))

the result is

["9:00 AM","9:30 AM","10:00 AM","10:30 AM","11:00 AM","11:30 AM","12:00 PM","12:30 PM","1:00 PM","1:30 PM","2:00 PM","2:30 PM","3:00 PM","3:30 PM","4:00 PM","4:30 PM","5:00 PM","5:30 PM","6:00 PM","6:30 PM","7:00 PM","7:30 PM","8:00 PM","8:30 PM","9:00 PM","9:30 PM","10:00 PM"]

but for 1 hour(60)

["9:00 AM","9:60 AM","10:00 AM","10:60 AM","11:00 AM","11:60 AM","12:00 PM","12:60 PM","1:00 PM","1:60 PM","2:00 PM","2:60 PM","3:00 PM","3:60 PM","4:00 PM","4:60 PM","5:00 PM","5:60 PM","6:00 PM","6:60 PM","7:00 PM","7:60 PM","8:00 PM","8:60 PM","9:00 PM","9:60 PM","10:00 PM"]

Solution

  • Your interval should be based off of minutes. Add the minutes to the start time. Convert the total minutes to HH:MM. (note I did not do the AM/PM, you can figure that out)

    function getMins(time) {
      const parts = time.split(":");
      return +parts[0] * 60 + +parts[1];
    }
    
    function convertMins(totalMinutes) {
      const minutes = (totalMinutes % 60).toString().padStart(2, '0');
      let hrs = (totalMinutes-minutes)/60;
      const hours = hrs.toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    }
    
    function getTimes(start, end, timeInterval = 30) {
      const startMins = getMins(start);
      const endMins = getMins(end);
      return Array.from({ length: Math.ceil((endMins - startMins) / timeInterval) + 1 })
        .map((_, i) => convertMins( Math.min(startMins + i * timeInterval, endMins)));
    }
    
    
    console.log(getTimes("9:00", "22:00"))
    console.log(getTimes("9:00", "22:00", 20))
    console.log(getTimes("9:00", "22:00", 60))
    console.log(getTimes("9:00", "22:00", 35))
    console.log(getTimes("9:00", "22:00", 180))