user3176663 user3176663 - 5 months ago 8
PHP Question

How to format time 12:00:00 or 12:00:am to 12:00 AM?

I am using strtotime()
its working fine for $time = '12:00:00';
but

$time = '12:00:am';
echo date('h:i A ', strtotime($time));


it return 4:00 PM but I want output is 12:00 AM

Answer

This Function could help you. It takes a time like your format "12:00:00 or 12:00:am" and output it's as your needs like this "12:00 AM" .

function convert_time($the_time){
    $time_arr = explode(":",$the_time);
    if($time_arr[2] != "am" || $time_arr[2] != "pm"){
        if($time_arr[0] >= "0" && $time_arr[0] <= 12){
            if($time_arr[0] == 12 && $time_arr[1] > 00){
                $time_arr[2] = "pm";
            } else {
                $time_arr[2] = "am";
            }
        } else {
            $time_arr[2] = "pm";
        }
        $new_time = $time_arr[0].":".$time_arr[1]." ".strtoupper($time_arr[2]);
        return $new_time;
    }
    $new_time = $time_arr[0].":".$time_arr[1]." ".strtoupper($time_arr[2]);
    return $new_time;
}

$time = '12:00:am'; 
echo convert_time($time);