Reza Karami Reza Karami - 1 month ago 6x
jQuery Question

How to format an array of selected timeslots into a formatted string

I'm working with a scheduling system where users are able to choose timeslots in a day with half an hour intervals, where the selected timeslots array would look something like this:

['12:30', '13:00', '16:00', '16:30', '18:00']

I would like to display this to the user in a well-formatted output, ideally as the following:

"12:30pm - 1:30pm, 4:00pm - 5:00pm, 6:00pm - 6:30pm"

I can handle the 24hr to 12hr conversion but I can't wrap my head around how to format the time ranges and group them if they're consecutive half-hour slots.

I'm using moment.js, but I'm open to using other plugins if needed.

If a single, non-consecutive timeslot is chosen, such as 18:00, then the output based on the half-hour interval should be "6:00pm - 6:30pm".


You need first parse the date then use .format() method to transform the it into desired format.

var arr = ['12:30', '13:00', '16:00', '16:30'];
var newArr = {
  return moment(dt, 'HH:mm').format('hh:mmA');

//Example, However it will not work if newArr is length of 3, 5
var nArr = [];
for (var i = 0; i < newArr.length; i += 2) {
  nArr.push(newArr[i] + ' ' + newArr[i + 1])

<script src=""></script>