Software Developer

Convert Time From 24-hour Format to 12-hour Format

This is a PHP function to convert time from 24-hour format (HH:MM) into 12-hour format, with am or pm added. It takes two parameters:

  1. the hour
  2. the minute (with a leading zero for 0 through 9)

It returns the time in 12-format like this: HH:MM am/pm

/**
 * convert 24-hour time format into 12-hour time format
 * @param int, the hour in 24-hour format, 0 - 23
 * @param int, minutes, 00 to 59, with a leading zero for 0 through 9
 * returns string, time in 12-hour format "HH:MM am/pm"
 */

function time24to12($h24, $min) {
    if ($h24 == 0) { $newhour = 12; }
	elseif ($h24 <= 12) { $newhour = $h24; }
	elseif ($h24 > 12) { $newhour = $h24 - 12; }
    return ($h24 < 12) ? $newhour . ":$min am" : $newhour . ":$min pm";
}

See more: ,

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]