ThePsion5 Posted December 12, 2007 Share Posted December 12, 2007 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: 3Into this:3AM to 4 AMHere'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 More sharing options...
justsomeguy Posted December 12, 2007 Share Posted December 12, 2007 You forgot to set $IsAM back to false before you test the next hour. Link to comment Share on other sites More sharing options...
ThePsion5 Posted December 13, 2007 Author Share Posted December 13, 2007 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 More sharing options...
justsomeguy Posted December 13, 2007 Share Posted December 13, 2007 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 More sharing options...
Synook Posted December 13, 2007 Share Posted December 13, 2007 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 More sharing options...
justsomeguy Posted December 13, 2007 Share Posted December 13, 2007 Whoops. Good catch. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.