How could I split time every X minutes, if I know the start time and end time. So for instance, if my start time is 13:00 and my end time is: 15:00 and splitting it every 30 minutes, then I would like to get an array containing:
13:00 - 13:30
14:00 - 14:30
14:30 - 15:00
13:00 - 13:30
13:30 - 14:00
14:00 - 14:30
14:30 - 15:00
see it in action
var makeTimeIntervals = function (startTime, endTime, increment) {
startTime = startTime.toString().split(':');
endTime = endTime.toString().split(':');
increment = parseInt(increment, 10);
var pad = function (n) { return (n < 10) ? '0' + n.toString() : n; },
startHr = parseInt(startTime[0], 10),
startMin = parseInt(startTime[1], 10),
endHr = parseInt(endTime[0], 10),
endMin = parseInt(endTime[1], 10),
currentHr = startHr,
currentMin = startMin,
previous = currentHr + ':' + pad(currentMin),
current = '',
r = [];
do {
currentMin += increment;
if ((currentMin % 60) === 0 || currentMin > 60) {
currentMin = (currentMin === 60) ? 0 : currentMin - 60;
currentHr += 1;
}
current = currentHr + ':' + pad(currentMin);
r.push(previous + ' - ' + current);
previous = current;
} while (currentHr !== endHr);
return r;
};
var a = makeTimeIntervals('13:00', '15:00', 30);
for (var i in a) if (a.hasOwnProperty(i)) { document.body.innerHTML += a[i] + '<br />'; }
You can use datejs and its add method to add minutes to your Date object. The compareTo method can be used to check that you are still within the appropriate range.
If you don't want to use an external library, you can refer to W3Schools.
// Set minutes.
var myDate = new Date();
myDate.setMinutes(myDate.getMinutes() + 30);
// Compare two dates.
var x = new Date();
x.setFullYear(2100, 0, 14);
var today = new Date();
if (x > today) {
alert("Today is before 14th January 2100");
} else {
alert("Today is after 14th January 2100");
}
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