<?php
/**
* Truncates time values for quick fixes and sanity checks.
*
* @param string $time_value The time value to truncate (e.g., "2023-10-27 10:30:45").
* @param string $format The desired output format (e.g., "Y-m-d H:i:s", "Y-m-d"). Defaults to "Y-m-d".
* @return string The truncated time value, or an empty string on error.
*/
function truncateTime(string $time_value, string $format = "Y-m-d"): string
{
if (empty($time_value)) {
return ""; // Handle empty input
}
try {
$datetime = \DateTime::createFromFormat('Y-m-d H:i:s', $time_value); // Attempt to parse with full timestamp
if ($datetime === false) {
$datetime = \DateTime::createFromFormat('Y-m-d', $time_value); //Try parsing without time
}
if ($datetime === false) {
return ""; //Handle invalid date format
}
return $datetime->format($format); // Format the date according to specified format
} catch (\Exception $e) {
return ""; // Return empty string on any exception
}
}
//Example Usage
if(isset($_GET['time'])) {
$time = $_GET['time'];
$truncated_time = truncateTime($time);
echo $truncated_time;
}
?>
Add your comment