Abi*_*din 0 php mysql time datetime date
我有一个数据库,其时间按TIME格式存储00:00:00。数据库接受NULL,但我还使用将时间转换为 12 小时格式的函数,仅供查看。
问题是:当时间输入为空时,转换格式的函数正在更改我可以接受的格式NULL,但在将其转换回 12 小时时间时00:00:00我无法让它不打印。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;
}
Run Code Online (Sandbox Code Playgroud)
你在这里有点虐待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;
}
Run Code Online (Sandbox Code Playgroud)
(如果您想变得更奇特,您可以对输入进行正则表达式检查,而不仅仅是检查是否为空。)
现在这应该可以按照您的要求工作:
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";
Run Code Online (Sandbox Code Playgroud)
结果:
11:34:29 PM
23:34:29
Run Code Online (Sandbox Code Playgroud)