Validate a date in PHP

If you have to validate a date coming from an HTML widget (year, month, day <select> elements or a date picker), or any other input, you still have to make sure that the date being processed is valid.

Validation here means that "December 0, 2019" and "December -1, 2019" are invalid, as well as "February 30", "February 31", "April 31" or "September 35, 2022", as well as "February 29, 2022", but not "February 29, 2020".

The timestamp behind the datetime is a Unix integer.

  • "December 0, 2019" becomes "November 30, 2019"
    • because the timestamp of "December 0, 2019" is the integer of "November 30, 2019".
  • "December -1, 2019" becomes "November 29, 2019".
  • "February 30, 2022" becomes "March 2, 2022".
  • "February 31, 2022" becomes "March 3, 2022".
  • "April 31, 2022" becomes "May 1, 2022".
  • "September 35, 2022" becomes "October 5, 2022".

Even if you create dynamic validators for your date picker to prevent certain values to be entered in the widget, you still should check the value before it goes in the HTTP response.

Code

We use checkdate().

Result

Boolean is returned.

checkdate(12, 0, 2019);  //=> false
checkdate(12, -1, 2019); //=> false
checkdate(2, 29, 2020);  //=> true
checkdate(2, 29, 2021);  //=> false
checkdate(2, 30, 2022);  //=> false
checkdate(2, 31, 2022);  //=> false
checkdate(4, 31, 2022);  //=> false
checkdate(9, 35, 2022);  //=> false