1. <?php
  2. /**
  3. * Checks date constraints for data migration.
  4. *
  5. * @param string $date_string The date string to validate (e.g., 'YYYY-MM-DD').
  6. * @param string $format The expected date format (e.g., 'Y-m-d').
  7. * @param int|null $min_date Optional minimum date for validation.
  8. * @param int|null $max_date Optional maximum date for validation.
  9. * @return bool True if the date is valid and within the specified range, false otherwise.
  10. */
  11. function validateDate(string $date_string, string $format, ?int $min_date = null, ?int $max_date = null): bool
  12. {
  13. // Attempt to create a DateTime object
  14. $dateTime = DateTime::createFromFormat($format, $date_string);
  15. // Check if the date is valid
  16. if ($dateTime === false) {
  17. return false; // Invalid date format
  18. }
  19. // If min_date is specified
  20. if ($min_date !== null && $dateTime < new DateTime($min_date)) {
  21. return false; // Date is before the minimum date
  22. }
  23. // If max_date is specified
  24. if ($max_date !== null && $dateTime > new DateTime($max_date)) {
  25. return false; // Date is after the maximum date
  26. }
  27. return true; // Date is valid and within range
  28. }
  29. //Example usage
  30. /*
  31. $date = '2023-10-27';
  32. $format = 'Y-m-d';
  33. $minDate = 20230101;
  34. $maxDate = 20231231;
  35. if (validateDate($date, $format, $minDate, $maxDate)) {
  36. echo "Date is valid.\n";
  37. } else {
  38. echo "Date is invalid.\n";
  39. }
  40. */
  41. ?>

Add your comment