raqulka raqulka - 2 months ago 11
jQuery Question

How to create an array of times from in jquery with one hour interval?

I searched around a lot, and found some examples, but non of those did not work as expected. I am trying to create available time slots to specific day and would like to display times like this:

10.00 | available

11.00 | available

12-00 | available

13.00 | available

etc.

For example right now start times at 16.00 (current time in my timezone UTC+02:00), rest of the times should be disabled. Then tomorrow start from 00.00 again. How should I make that work?

What I have right now is this:

var arr = [], i, j;
for(i=0; i<24; i++) {
for(j=0; j<1; j++) {
arr.push(i + ":" + ("00") );
}
}

var d = new Date(),
h = d.getHours(),
m = 15 * Math.floor(d.getMinutes() / 15),
stamp = h + ":" + (m === 0 ? "00" : m);

var pos = arr.indexOf(stamp),
timelist = arr.slice(pos).concat(arr.slice(0, pos));

console.log(arr);


which gives me this

["0:00", "1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"]

Answer

Why cut the array, instead get the actual hour and change your for loop:

var date = new Date;
var hour = date.getHours();

var arr = [];
for(var i=hour; i<24; i++) {
  arr.push(i + ":00") );
}
console.log(arr);

If you want to show the past times as well, why not make two arrays:

var date = new Date;
var hour = date.getHours();

var pastHours = [],
    futureHours = [];
for( var i=0; i<hour; i++ ) {
  pastHours.push(i+":00");
}
for(var i=hour; i<24; i++) {
  futureHours.push(i + ":" + ("00") );
}
console.log(pastHours);
console.log(futureHours);

Or in one array:

var arr = [];
for( var i=0; i<24; i++ ) {
  arr.push(i+":00");
}

var date = new Date,
    hour = date.getHours(),
    hourIndex = arr.indexOf(hour+":00");

var pastHours = arr.slice(0,hourIndex);
var futureHours = arr.slice(hourIndex);

console.log(pastHours);
console.log(futureHours);