oddsblogs


::::: January 26, 2007 at 9:44 pm

Converting time from 24-hour (military) to 12-hour (AM/PM) in PHP

Today I was writing some code in PHP for a weekly schedule and found a need to convert an integer equivalent of an hour in 24-hour format to 12-hour format. So there was some table layout, and each cell represented an hour period of one day of the week.

I searched the PHP forums, but this really isn’t a “date and time” issue (as far as PHP functions for real dates and times are concerned). It could be that a solution is listed there, but I couldn’t find it quickly. What can I say, my attention span is measured in nanoseconds.

I was using integers for the hour loop, so they were in military time. I needed a quick and dirty function to convert these integers to 12-hour format. This is what I ended up with.

I’m a big fan of ternary operators, they can really make your code compact.

Popularity: 85%

By Billy ::::: Permalink :::::
See Related Stories In: Programming

6 Comments »

March 2, 2007 @ 11:20 am #

I’ll use that, cheers.

 

March 7, 2007 @ 8:42 am #

I changed it a bit, useful if you want to convert true military time, ie. 0800, 2350, 0622

function twelveHourTime($twentyFour) {
$ampm = ($twentyFour >=1200 && $twentyFour

 

March 7, 2007 @ 8:50 am #

function twelveHourTime($twentyFour) {
$ampm = ($twentyFour >=1200 && $twentyFour [less than] 2400) ? “pm” : “am”;
$hour = (floor($twentyFour / 100) % 12 === 0) ? 12 : floor($twentyFour / 100) % 12;
$minute = ($twentyFour % 100 === 0) ? ‘00′ : $twentyFour % 100;
return “$hour:$minute $ampm”;
}

 

March 13, 2007 @ 3:16 pm #

miltoampm($hour) {
return (($hour%12)?$hour%12:12).’ ‘.(($hour>12)?’PM’:'AM’);
}

Does the same job and is shorter.

 

March 14, 2007 @ 12:54 pm #

Indeed…thanks for the tips etc.

 

July 8, 2007 @ 8:22 pm #

thnx man

 

RSS feed for comments on this post. TrackBack URI

Leave a comment

Name (required)