Problem with String Processing

i’ve 24 hour time variable like >
0100 for 1 AM,
0200 for 2 AM,
1200 for 12 Noon
1700 for 17 PM

and i want to echo those variable in “:” way, i.e.
0100 > 1:00
1700 > 17:00
how to do? please help me.

Hi,

This is pretty simple, you know your variable will always be 4 digits.

[php]
$time = “0100”; //1 AM, for example
$hour = substr($time,0,2); //sets $hour to the first two digits of $time
$min = substr($time,2,2); //sets $min to the last two digits of $time
if($hour<10) { $hour = str_replace(“0”, “”, $hour); } //removes the leading zero from hours, if you want, otherwise exclude this, note, will turn 00 into “”
if($hour<12) { $half = “AM”; } else { $half = “PM”; }
if($hour>12) { $hour = $hour - 12; } //changes format into 12 hour instead of 24 hour, so 13:00 becomes 1:00
if($hour == “”) { $hour = “12”; } //in the case of $hour 00, which became $hour “”, set $hour to 12
$newTime = $hour.’:’.$min.’ '.$half; // sets $newTime to $hour:$min $half, or in this case, outputs 1:00 AM
[/php]

Hope this helps.

Robert

Sponsor our Newsletter | Privacy Policy | Terms of Service