I need to create an array of elements in javascript, which add 2 hours to a certain time I set. I give an example. The time is
14:00.
I need, to create an array that contains all 30 minute intervals up to 16:00.
Ex
14:00
14:30
15:00
15:30
Here is a function that produces the time specifications as strings. It can take an optional second argument to specify the end-time (16:00 in your question).
Two utility functions convert a time string to (and from) a number of minutes.
Finally, the result array is created with Array.from:
const toMinutes = str => str.split(":").reduce((h, m) => h * 60 + +m);
const toString = min => (Math.floor(min / 60) + ":" + (min % 60))
.replace(/\b\d\b/, "0$&");
function slots(startStr, endStr="16:00") {
let start = toMinutes(startStr);
let end = toMinutes(endStr);
return Array.from({length: Math.floor((end - start) / 30) + 1}, (_, i) =>
toString(start + i * 30)
);
}
console.log(slots("14:00"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With