我有一个数据库,其中的时间存储为 TIME
,格式为 00:00:00
。数据库接受 NULL
,但我也使用将时间转换为 12 小时格式的函数,仅供查看。
问题是:当时间输入为空时,转换格式的函数正在将 NULL
更改为 00:00:00
我会接受的,但我无法让它在将其转换回 12 小时制时不打印 12:00 AM
。
我需要:
- 将输入作为
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;
}
最佳答案
您在这里有点滥用 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
关于php时间处理NULL为00 :00:00,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53230199/