Airikr
Airikr

Reputation: 6436

Loop each hour to the same hour tomorrow

I want to get each hours from the current hour and 24 hours ahead (21:00 tonight to 21:00 tomorrow). The loop below just loops to 24.

var i;
var date = new Date;
var hours = date.getHours();

for(i = hours; i <= 24; i++) {
    console.log(i);
}

What should I do to accomplish this?

Demo: http://jsfiddle.net/edgren/64XDf/

Upvotes: 0

Views: 1709

Answers (3)

Fabricator
Fabricator

Reputation: 12772

Use modular arithmetic

for(i = 0; i <= 24; i++) {
    console.log((i+hours)%24);
}

show 24 for hour 0:

for(i = 0; i <= 24; i++) {
    var h = (hours+i)%24;
    if (h == 0) h = 24;
    console.log(h);
}

Upvotes: 5

Elliott Frisch
Elliott Frisch

Reputation: 201447

Your end condition is off by hours, and you need to adjust for the 24 hours limit. One solution is to do this,

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

for (var i = hours; i <= hours+24; i++) {
  console.log((i > 23) ? i - 24 : i);
}

Updated fiddle

Upvotes: 1

Dan
Dan

Reputation: 9468

Does this do what you're looking for?

var i;
var date = new Date;
var hours = date.getHours();

for(i = hours; i <= hours+24; i++) {
    if(i<25){
        console.log(i);
    }else{
        console.log(i-24);
    }
}

Updated fiddle

Upvotes: 1

Related Questions