Skip to content

Instantly share code, notes, and snippets.

@EdoardoVignati
Last active October 6, 2020 14:48
Show Gist options
  • Save EdoardoVignati/585ee739e840b35b5ff76af9febed996 to your computer and use it in GitHub Desktop.
Save EdoardoVignati/585ee739e840b35b5ff76af9febed996 to your computer and use it in GitHub Desktop.
Create a range of hours and minutes given start and end time in a day in Javascript
// Add to your html header
<script src="https://momentjs.com/downloads/moment.js"></script>
// Add these two functions
function buildInterval(start, end){
var range = [];
var time = moment.duration(start).asSeconds();
if(end<=start)
var endtime = moment.duration(end).asSeconds()+86400;
else
var endtime = moment.duration(end).asSeconds();
var step = 1800;
while(time <= endtime){
var formatted = padDigits(Math.floor(moment.duration(time,'seconds').asHours()%24),2) + ':' + padDigits(moment.duration(time,'seconds').minutes(),2);
range.push(formatted);
time=time+step;
}
console.log(JSON.stringify(range));
return range;
}
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
/*
Example:
buildInterval("23:00","22:30");
Output: ["23:00","23:30","00:00","00:30","01:00","01:30","02:00","02:30","03:00","03:30","04:00","04:30","05:00","05:30","06:00","06:30","07:00","07:30","08:00","08:30","09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30","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"]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment