1. <?php
  2. /**
  3. * Validates a timestamp string.
  4. *
  5. * @param string $timestamp_string The timestamp string to validate.
  6. * @param string $format The expected timestamp format (e.g., 'Y-m-d H:i:s').
  7. * @return bool True if the timestamp is valid, false otherwise.
  8. */
  9. function validateTimestamp(string $timestamp_string, string $format = 'Y-m-d H:i:s'): bool
  10. {
  11. // Check if the timestamp string is provided
  12. if (empty($timestamp_string)) {
  13. return false;
  14. }
  15. // Attempt to create a DateTime object from the timestamp string
  16. try {
  17. $dateTime = new DateTime($timestamp_string, new DateTimeZone('UTC')); //Use UTC to avoid timezone issues
  18. } catch (Exception $e) {
  19. // If DateTime fails to create an object, the timestamp is invalid
  20. return false;
  21. }
  22. // Check if the timestamp matches the expected format
  23. $dateTimeFormat = new DateTimeFormat($format);
  24. $dateTime->format($dateTimeFormat);
  25. // If the timestamp is valid, return true
  26. return true;
  27. }
  28. /**
  29. * Validates an array of timestamps.
  30. *
  31. * @param array $timestamp_array An array of timestamp strings.
  32. * @param string $format The expected timestamp format (e.g., 'Y-m-d H:i:s').
  33. * @return array An array of validation results (true/false for each timestamp).
  34. */
  35. function validateTimestampArray(array $timestamp_array, string $format = 'Y-m-d H:i:s'): array
  36. {
  37. $results = [];
  38. foreach ($timestamp_array as $timestamp_string) {
  39. $results[] = validateTimestamp($timestamp_string, $format);
  40. }
  41. return $results;
  42. }
  43. ?>

Add your comment