A simple method to validate a date or check the date is true to the Gregorian calendar in PHP by defining the month, day and year.
PHP checkdate() will return true on a valid date and false when the date is not valid/doesn’t exist.
The parameters passed into the function are month, day and year as integers.
Examples
<?php $year = 2021; $month = 4; $day = 30; if (checkdate($month, $day, $year)) { echo "Valid date"; } else { echo "Not a valid date"; }
This will return ‘Valid date’
<?php $year = 2021; $month = 4; $day = 31; if (checkdate($month, $day, $year)) { echo "Valid date"; } else { echo "Not a valid date"; }
Returns ‘Not a valid date’ because April 2021 only has 30 days, there is no 31st.
Using this method is about matching to the Gregorian calendar rather than the date string format. Meaning you have to already have determined that your inputs are integers of their intended parameter.