Reputation: 167
I have a database with times stored as TIME
as in 00:00:00
format. The database accepts NULL
, but I also use functions that convert the time to a 12-hour format for viewing only.
The problem is: when the time input is empty, the functions that convert the format are changing the NULL
to 00:00:00
which I would be fine with, but I cannot get it to not print 12:00 AM
when converting it back to 12-hour time.
I need to either:
NULL
not 00:00:00
OR
00:00:00
to 12-hour time.These are the variations of the functions I have been using, again it is working if the value is a real time.
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;
}
Upvotes: 0
Views: 1766
Reputation: 42681
You're kind of abusing strtotime()
here. What you want to be doing is using PHP's date formatting functions:
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;
}
(If you wanted to get fancy you could do a regular expression check on the input, instead of just checking for empty.)
Now this should work as you're looking for:
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";
Result:
11:34:29 PM
23:34:29
Upvotes: 5