Click to See Complete Forum and Search --> : PHP Date Formatting
scaiferw
06-01-2005, 09:59 PM
I have times stored in a database as numeric in 24hr format that I wish to display in am/pm format, i.e. 1800 would become 6:00pm.
Nothing I've found will tell me how to do this. Can anyone help me out?
As I'm just developing this it's no big worry to change how I store the data.
Thanks,
Rob
HaganeNoKokoro
06-01-2005, 10:20 PM
<?php
function to12HourClock($time) {
$result=pad($time, 4);
$ampm="AM";
if($time>1159) $ampm="PM";
if($time<100) $result+=1200;
if($time>=1300) $result-=1200;
return substr($result, 0, 2).":".substr($result, 2, 2)." ".$ampm;
}
function pad($str, $n) {
$padding="";
for($i=strlen($str); $i<$n; $i++) $padding.="0";
return $padding.$str;
}
echo to12HourClock("0915");
?>
NogDog
06-01-2005, 11:00 PM
I would save it as a TIME type column in the database (HHMMSS). Then when you need it in am/pm format, let the query do the conversion:
SELECT TIME_FORMAT(`time_column`, '%h:%s%p') FROM `table` WHERE...