1. <?php
  2. /**
  3. * Truncates time values for quick fixes and sanity checks.
  4. *
  5. * @param string $time_value The time value to truncate (e.g., "2023-10-27 10:30:45").
  6. * @param string $format The desired output format (e.g., "Y-m-d H:i:s", "Y-m-d"). Defaults to "Y-m-d".
  7. * @return string The truncated time value, or an empty string on error.
  8. */
  9. function truncateTime(string $time_value, string $format = "Y-m-d"): string
  10. {
  11. if (empty($time_value)) {
  12. return ""; // Handle empty input
  13. }
  14. try {
  15. $datetime = \DateTime::createFromFormat('Y-m-d H:i:s', $time_value); // Attempt to parse with full timestamp
  16. if ($datetime === false) {
  17. $datetime = \DateTime::createFromFormat('Y-m-d', $time_value); //Try parsing without time
  18. }
  19. if ($datetime === false) {
  20. return ""; //Handle invalid date format
  21. }
  22. return $datetime->format($format); // Format the date according to specified format
  23. } catch (\Exception $e) {
  24. return ""; // Return empty string on any exception
  25. }
  26. }
  27. //Example Usage
  28. if(isset($_GET['time'])) {
  29. $time = $_GET['time'];
  30. $truncated_time = truncateTime($time);
  31. echo $truncated_time;
  32. }
  33. ?>

Add your comment