5

I'm not very good at Javascript Time manipulation.

Here is what I am trying to do: I have a UI that needs a end time drop down list. Its a finite set of times, essentially from 7:00 AM to 10:00 PM in 15 minute increments. I'm using jQuery and want to create on the fly a Select box that looks like this:

<select>
<option value="420">7:00 AM</option>
<option value="435">7:15 AM</option>
<option value="450">7:30 AM</option>
etc...
</select>

Anyone know how to do this in javascript/jQuery. I want to do something dynamic like this:

for(int i = 420; i<=1320; i+=15){
//use value of i to increment a date or something and create an option for the drop down... this is where I am stuck
}
Kara
  • 6,115
  • 16
  • 50
  • 57
Matt
  • 3,638
  • 2
  • 26
  • 33
  • Just have one variable for the hour and one variable for the minute. Increment the minute variable by 15 minutes and increment the hour variable if the minute variable goes over 60. It would most likely be less efficient and have less overhead than using a date. – Hello71 Jan 18 '12 at 22:13

1 Answers1

22

The following snippet should help you get the idea:

function populate(selector) {
    var select = $(selector);
    var hours, minutes, ampm;
    for(var i = 420; i <= 1320; i += 15){
        hours = Math.floor(i / 60);
        minutes = i % 60;
        if (minutes < 10){
            minutes = '0' + minutes; // adding leading zero
        }
        ampm = hours % 24 < 12 ? 'AM' : 'PM';
        hours = hours % 12;
        if (hours === 0){
            hours = 12;
        }
        select.append($('<option></option>')
            .attr('value', i)
            .text(hours + ':' + minutes + ' ' + ampm)); 
    }
}

populate('#timeSelect'); // use selector for your select
bzlm
  • 9,626
  • 6
  • 65
  • 92
Li0liQ
  • 11,158
  • 35
  • 52