Click to See Complete Forum and Search --> : Simple time function


art6
04-22-2007, 11:28 PM
Hi,

I'm just getting started with php and wrote a simple function that uses timestamps to find the angle formed by the hour, minute and second hands on a traditional clock. I was hoping someone could look it over and see if i'm writing it corrently. The function works as expected, I just wanted to see if there was a better or more efficient way of writing it. Also, is it possible to use a function (ie: time()) as the default value of a function parameter, I tried but couldn't get it to work.

Thanks!

// Function timeangle
// This function takes a UNIX timestamp and finds the angle
// of the hour, minute and second hands on a clock.
//
// Returns an associative array with h, m, s pointing to each of the found angles

function timeangle($time)
{

// if time is left empty use current time
$time = (!$time) ? time() : $time;

// create an array with values for hour, minutes and seconds and convert
// each to seconds
$time = array("h" => ((date("g", $time)) * 60 * 60),
"m" => ((date("i", $time)) * 60) ,
"s" => date("s", $time));

// convert each value to an angle
$time["h"] = (($time['h'] + $time['m'] + $time['s']) * 360) / 43200;
$time["m"] = (($time['m'] + $time['s']) * 360) / 3600;
$time["s"] = ($time['s'] * 360) / 60;


// Return array
return $time;


}

bradgrafelman
04-23-2007, 01:31 AM
Also, is it possible to use a function (ie: time()) as the default value of a function parameter, I tried but couldn't get it to work.I believe the default value for variables in a function declaration must be strings, not the output of another function. You pretty much have the gist of assigning a default value in this manner, though; I would only make two changes:

function timeangle($time=FALSE)
{

// if time is left empty use current time
$time = ($time === FALSE) ? time() : $time;

kilo dB
04-24-2007, 06:16 PM
If you make the names of the input and output variables different, then you can be more efficient:

//convert to angles
$angle['s'] = 6 * date('s', $time); //360/60 = 6
$angle['m'] = (angle['s']/360) + (6 * date('i', $time));
$angle['h'] = (angle['m']/360) + (30 * date("g", $time));

then return $angle, of course!