<?php
/**
* Validates a timestamp string.
*
* @param string $timestamp_string The timestamp string to validate.
* @param string $format The expected timestamp format (e.g., 'Y-m-d H:i:s').
* @return bool True if the timestamp is valid, false otherwise.
*/
function validateTimestamp(string $timestamp_string, string $format = 'Y-m-d H:i:s'): bool
{
// Check if the timestamp string is provided
if (empty($timestamp_string)) {
return false;
}
// Attempt to create a DateTime object from the timestamp string
try {
$dateTime = new DateTime($timestamp_string, new DateTimeZone('UTC')); //Use UTC to avoid timezone issues
} catch (Exception $e) {
// If DateTime fails to create an object, the timestamp is invalid
return false;
}
// Check if the timestamp matches the expected format
$dateTimeFormat = new DateTimeFormat($format);
$dateTime->format($dateTimeFormat);
// If the timestamp is valid, return true
return true;
}
/**
* Validates an array of timestamps.
*
* @param array $timestamp_array An array of timestamp strings.
* @param string $format The expected timestamp format (e.g., 'Y-m-d H:i:s').
* @return array An array of validation results (true/false for each timestamp).
*/
function validateTimestampArray(array $timestamp_array, string $format = 'Y-m-d H:i:s'): array
{
$results = [];
foreach ($timestamp_array as $timestamp_string) {
$results[] = validateTimestamp($timestamp_string, $format);
}
return $results;
}
?>
Add your comment