0

Can't figure this out, from 9:00 to 10:00 everything's correct, but then it all goes haywire. after 10:00 it jumps to 11:15 and then to 12:30

I am simply adding minutes to a date/time to increment an array in 15 minute intervals, is it that I can only add a maximum of 60 minutes ??

function pad(val,max) { 
        var str = val.toString(); 
        return str.length < max ? pad("0" + str, max) : str;
}

function cboHrs(){
    var now = new Date(); 
    now.setHours(9);
    var hrs = [];
    for (var i=1;i<36;i++){
        var hr = {}; 
        now.setMinutes(i*15);
        hr.txt = pad(now.getHours(),2) +':'+pad(now.getMinutes(),2);
        hr.val = hr.txt; 
        hrs.push(hr);
        }
    return hrs;
}
console.log(cboHrs());
1
  • Can you post the pad function? Commented Mar 20, 2013 at 12:11

2 Answers 2

3

Anthony got to the actual problem before me...

After the 5th iteration, you are setting the minutes to become 75 (ie, 5 * 15 = 75) which is an 1 hour and 15 minutes which is why the next value after 10:00 becomes 11:15 - Anthony Forloney

This code should work to set the time correctly.

function cboHrs(){
    var now = new Date(); 
    var hrs = [];
    for (var i=1;i<36;i++){
        var hr = {};
        // add another hour every 4th iteration
        now.setHours(9 + parseInt(i / 4));
        // add 15 minutes every iteration, starting back at 0 on the 4th
        now.setMinutes((i % 4) * 15);
        hr.txt = pad(now.getHours(),2) +':'+pad(now.getMinutes(),2);
        hr.val = hr.txt; 
        hrs.push(hr);
        }
    return hrs;
}
Sign up to request clarification or add additional context in comments.

1 Comment

No problem. I actually would have expected the same behavior you were expecting and as a result would have run into the same problem, so I'm glad this question got me thinking about it, potentially saving me, and hopefully others, some time.
2

The problem lies within the now.setMinutes(i*15); line of code. After the 5th iteration, you are setting the minutes to become 75 (ie, 5 * 15 = 75) which is an 1 hour and 15 minutes which is why the next value after 10:00 becomes 11:15

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.