如何格式化时间为12:00:00或12:00:上午12:00?

时间:2016-07-05 14:00:16

标签: php codeigniter

我正在使用strtotime() 它工作正常$ time = '12:00:00'; 但是

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

它返回下午4:00,但我希望输出是12:00 AM

1 个答案:

答案 0 :(得分:1)

此功能可以帮助您。您的格式需要一段时间“12:00:00或12:00:am”,并根据您的需要将其输出为“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);