php时间处理null为00:00:00

xkrw2x1b  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(471)

我有一个存储时间的数据库 TIME 如在 00:00:00 格式。数据库接受 NULL ,但我也使用函数将时间转换为12小时格式,仅用于查看。
问题是:当时间输入为空时,转换格式的函数正在更改格式 NULL00:00:00 我可以接受,但我不能不把它打印出来 12:00 AM 当它转换回12小时的时间。
我需要:
将输入作为 NULL 不是 00:00:00
转换时不显示任何内容 00:00:00 到12小时的时间。
这些是我一直在使用的函数的变体,如果值是实时的,它同样工作。

function time_12_to_24_sql ($value, $default) {
    $time = $_POST[$value];

    return ((!array_key_exists($value,$_POST)) || $_POST[$value] == NULL) ? $defaultValue : date("H:i:s", strtotime($time));
}

function time_12_to_24 ($input) {

if($input == NULL) {
    $retVal = $input;
}
if($input == 'NULL') {
    $retVal = $input;
}
if (!isset($input)) {
    $retVal = NULL;
}
if($input == '12:00 AM') {
    $retVal = NULL;
}
if($input == '') {
    $retVal = NULL;
}
else {
    $retVal = date("H:i:s", strtotime($input));
}
return $retVal;
}

function time_24_to_12 ($input) {
    if($input == NULL) {
        $retVal = $input;
    }
    if (strtotime($input) == '00:00:00') {
        $retVal = '';
    }
    if ($input == '') {
        $retVal = '';
    }
    if (!isset($input)) {
        $retVal = '';
    }
    else {
        if(strtotime($input) > 0){ 
            $retVal = date("g:i A", strtotime($input));
        }
    }
    return $retVal;
}
xyhw6mcr

xyhw6mcr1#

你在虐待我 strtotime() 在这里。您要做的是使用php的日期格式化函数:

function time_24_to_12 ($input) {
    // empty checks for null, empty string, zero, false, unset, etc.
    if (empty($input)) {
        return "";
    }
    $date = DateTime::createFromFormat("H:i:s", $input);
    $time = $date->format("h:i:s A");
    return ($time === "12:00:00 AM") ? "" : $time;
}

function time_12_to_24 ($input) {
    if (empty($input)) {
        return "";
    }
    $date = DateTime::createFromFormat("h:i:s A", $input);
    $time = $date->format("H:i:s");

    return ($time === "00:00:00") ? "" : $time;
}

(如果您想想象一下,您可以对输入执行正则表达式检查,而不只是检查是否为空。)
现在,这应该可以满足您的要求:

echo time_24_to_12("23:34:29") . "\n";
echo time_24_to_12("00:00:00") . "\n";
echo time_24_to_12("") . "\n";

echo time_12_to_24("11:34:29 PM") . "\n";
echo time_12_to_24("12:00:00 AM") . "\n";
echo time_12_to_24(null) . "\n";

结果:

11:34:29 PM

23:34:29

相关问题