Handling Dates in yyyy-mm-dd Format in PHP with the DateTime Class

Accepting and Validating the Date Input

Assuming one's input (in format 'yyyy-mm-dd') is incoming in the below $date variable:

$dt = \DateTime::createFromFormat("Y-m-d", $date);

Following the strategy found in this Stack Overflow answer - https://stackoverflow.com/a/13194398, check if the input is valid:

if($dt !== false && !array_sum($dt->getLastErrors())){
  echo "Valid date - continuing.\n";
}else{
  echo "Invalid date - please ensure you provide a date in YYYY-MM-DD format.\n";
  return false;
}

Further explanation from the answer about the validation technique:

This validates the input too: $dt !== false ensures that the date can be parsed with the specified format and the array_sum trick is a terse way of ensuring that PHP did not do "month shifting" (e.g. consider that January 32 is February 1). See DateTime::getLastErrors() for more information.

Using the Input

Often it is necessary to echo the date validated above, though this can cause errors since the $dt variable is a DateTime object and not a string.  In order to format it as a string, use the following technique:

$dt = $dt->format('Y-m-d');

Tags

 PHP  snippets  dates  PHP DateTime