I have a select dropdown with times in 30 min intervals like
11:00 AM, 11:30 AM, 12:00 PM, 12:30 PM, 1:00 PM
beginning from 0:00 AM and ending with 11:30 PM
<select id='time'>
<option value="11:30 AM">11:30 AM</option>
<option value="12:00 PM">12:00 PM</option>
<option value="12:30 PM">12:30 PM</option>
<option value="1:00 PM">1:00 PM</option>
<option value="1:30 PM">1:30 PM</option>
<option value="2:00 PM">2:00 PM</option>
<option value="2:30 PM">2:30 PM</option>
<option value="3:00 PM">3:00 PM</option>
<option value="3:30 PM">3:30 PM</option>
<option value="4:00 PM">4:00 PM</option>
<option value="4:30 PM">4:30 PM</option>
</select>
$(document).ready(function(){
$('#time').val(.now()); // this wouldnt work it gives the current time which may be between 30 min
});
I want this select dropdown to default to rounded to nearest higher time based on current time.
For eg. if the current time is 10:46 AM then the selected value should 11:00 AM and if the current time is 10:31 AM should also default to 11:00 AM.
Any pointers on achieving this using jquery or with normal javascript.
Thanks
You could use the Math.round
function to get the value to the nearest half hour:
Math.round(Date.now()/(30*60*1000))*(30*60*1000));
Construct a date object from this and get the time.
var date = new Date(Math.round(Date.now() / (30 * 60 * 1000)) * (30 * 60 * 1000));
$('#time').val(date.getHours()%12 + ":" + ("0"+date.getMinutes()).slice(-2) + " " + (date.getHours() >= 12 ? "PM" : "AM"));
Here is a demonstration: http://jsfiddle.net/GsR6v/9/
You can try to round the value of the Date something like this:
var date = new Date(Math.round(Date.now()/(30*60*1000))*(30*60*1000));
Then use this to set up the date:
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == <YourDate>;
}).attr('selected', true);
Try this on my fiddle: http://jsfiddle.net/mC869/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.