Web Development for 2012

Alexander Dickson - Web Developer covering PHP, jQuery / Javascript, XHTML, CSS, more

Building a list of hours with PHP

Published on Monday, 11th October 2010.

Have you ever been creating a form, and needed to know a time? A dropdown is the best way to get a time itself, IMO (or perhaps a masked input box).

When you see that you need to create times from, say, 8:00am to 4:00pm, using code springs to mind to make life easier.

I have crafted a small function to help create an array of times for PHP.

function hoursRange($lower = 0, $upper = 23, $step = 1, $format = NULL) {   if ($format === NULL) { $format = 'g:ia'; // 9:30pm } $times = array(); foreach(range($lower, $upper, $step) as $increment) { $increment = number_format($increment, 2); list($hour, $minutes) = explode('.', $increment); $date = new DateTime($hour . ':' . $minutes * .6); $times[(string) $increment] = $date->format($format); } return $times; }

I wrote something more bloated earlier today, but decided to spend some real time on it tonight. I'm pretty happy with it. I would like to know however if there was a better way of turning 0.5 into 30 though.

Comments

No comments yet.

Leave a Comment

Comment Details

Your email will never be displayed. If you have a gravatar, it will be displayed.

Note: Your comment may require approval before it is posted to the site.

Stack Overflow Profile

view full profile »

About

I'm a web developer from the Sunshine Coast, Australia. more »