简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM