DEV Community

pO0q 🦄
pO0q 🦄

Posted on

PHP: check dates

So many errors happen due to a malformed date or simply because of a wrong input.

Unfortunately, it's not uncommon apps don't check dates correctly or lack some validation rules.

Another common scenario is when the app does not catch enough exceptions, especially when you use the built-in PHP DateTime.

Use checkdate() for Gregorian dates

You may want to build your own helper, but be aware that checkdate() exists.

It takes a year, a month, and a day as inputs. You can easily combine it with date_parse() to extract the 3 arguments you need from a date string.

If possible, avoid regular expressions

I know this one may seem a bit opinionated, as good regular expressions (regex) can totally do the job.

However, it's possible to miss some edge cases, so prioritizing built-in helpers is more rewarding, in my experience.

Use DateTime::createFromFormat()

Instead of using new DateTime($date) directly, which will raise an error if the input is wrong, for example:

$date = '2031-31-31';
new DateTime($date);
Enter fullscreen mode Exit fullscreen mode

You can use the static DateTime::createFromFormat() that takes a format and a date string as inputs to validate the format before using your input, as it returns false when errors happen:

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}
Enter fullscreen mode Exit fullscreen mode

Source: glavic - PHP doc

This class is really powerful for further operations like:

  • converting dates from one format to another
  • getting date diffs
  • adding to an existing date

... and many more.

Leverage third-party libraries

Carbon is probably one of the most popular vendors to handle dates in PHP.

It's also quite common to use it for testing purposes (e.g., unit tests), allowing you to generate dates for your tests quite easily.

Carbon is a robust library that provides an extended API for DateTime.

It does not mean you should absolutely use it everywhere, but it can make sense for your case. Many frameworks, like Laravel use it to compose new projects.

Wrap up

Nothing new there, but validating dates is not optional. Otherwise, you will get some bugs or even allow unexpected behaviors.

Top comments (0)