Jump to content

Turning a Number (1-24) into a time (xx AM/xx PM)


ThePsion5

Recommended Posts

Hi guys,I'm working on a function to take a hour number (0-23) and turn it into a more human-readable format (12AM-11PM), and I'm having a hard time creating a function that does it properly. When functioning properly, it should turn this:

3
Into this:
3AM to 4 AM
Here's my current function, which works most of the time but still screws up in some places:
$IsAM = false;  $Hour = $input;  $NextHour = $input+1;  $r;  //Check the current hour  if($Hour < 12)	$IsAM = true;    if($input > 12)	$Hour -= 12;    if($IsAM)	$r = $Hour . ' AM to ';  else	$r = $Hour . ' PM to ';       //Check the next hour  if($NextHour < 12)	$IsAM = true;	    if($NextHour > 12)	$NextHour -= 12;      if($IsAM)	$r .= $NextHour . ' AM';  else	$r .= $NextHour . ' PM';

What am I missing?Thanks in advance for the help!

Link to comment
Share on other sites

Okay, I think I figured it out, although my method seems to be fairly inefficient:

$IsAM = false;  $Hour = $input;  $NextHour = $input+1;  $r;    //Reset the next hour to zero if needed  if($NextHour == 24)	$NextHour = 0;  //Check the current hour  if($Hour < 12)	$IsAM = true;    if($input > 12)	$Hour -= 12;    if($IsAM && $Hour==0)	$Hour = 12;    if($IsAM)	$r = $Hour . ' AM to ';  else	$r = $Hour . ' PM to ';         //Check the next hour  $IsAM = false;  if($NextHour < 12)	$IsAM = true;	    if($NextHour > 12)	$NextHour -= 12;      //Turn '0 AM' into '12 AM'  if($IsAM && $NextHour==0)	$NextHour = 12;      if($IsAM)	$r .= $NextHour . ' AM';  else	$r .= $NextHour . ' PM';       return $r;

Link to comment
Share on other sites

Yeah, not to burst your bubble but there are some built-in functions that will do this pretty quickly. That happens a lot with PHP, I write a big algorithm then find a function that does the same thing.$val1 = strtotime($input . ":00");$val2 = $val1 + (60 * 60);$r = date("g A", $val1) . " to " . date("g A", $val2);

Link to comment
Share on other sites

The above script is missing a concatenation operator for the last line, in case you use it

$val1 = strtotime($input . ":00");$val2 = $val1 + (60 * 60);$r = date("g A", $val1) . " to " . date("g A", $val2);

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...