将军队时间转换为PHP中的常规时间AM PM

tbr*_*y22 5 php time

我正在寻找一种方法将军队时间(例如23:00)转换为使用AM/PM表达式的常规时间.

sha*_*008 17

在这样的strtotime功能中度过你的时间:

$time_in_12_hour_format = date("g:i a", strtotime("23:00"));
echo $time_in_12_hour_format;
Run Code Online (Sandbox Code Playgroud)


Sco*_*tch 8

http://www.php.net/manual/en/function.date.php

$army_time_str = "23:00";
$regular_time_str = date( 'g:i A', strtotime( $army_time_str ) );
echo $regular_time_str;
Run Code Online (Sandbox Code Playgroud)


tbr*_*y22 3

输入$time的形式为'XXXX'(例如'0000'、'0001'、...、'2300')。我找不到这方面的功能,所以我写了以下内容。

function convert_army_to_regular($time) {
    $hours = substr($time, 0, 2);
    $minutes = substr($time, 2, 2);

    if ($hours > 12) {
        $hours = $hours - 12;
        $ampm = 'PM';
    } else {
        if ($hours != 11) {
            $hours = substr($hours, 1, 1);
        }
        $ampm = 'AM';
    }
    return $hours . ':' . $minutes . $ampm;
}
Run Code Online (Sandbox Code Playgroud)

  • 显而易见的答案是将其转换为 unix 时间戳或 DateTime 对象,然后使用 date() 或 DateTime format() 方法......如此干净和简单 (3认同)