2

How can I check that my string is a valid date ("2018-01-01").

Is there a simple way, or do I need to do something like this:

if (Carbon::createFromFormat('YOUR DATE FORMAT', $stringVariable) !== false) {
    // valid date
}
Mick
  • 1,401
  • 4
  • 23
  • 40

1 Answers1

0
$timestamp  = strtotime($date);

return $timestamp ? $date  : null ;
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • Although it works for the format "2018-01-01", it is worth remembering that for other date formats the result is false. for example, the date "13/10/2018" in the format "d/m/Y" is a valid date, but with strtotime, the result is false. – Magno Alberto Oct 13 '18 at 12:44
  • 1
    @MagnoAlberto The format d/m/Y is NOT a valid date format. If the separator is a slash (/), then the American `m/d/y` is assumed; whereas if the separator is a dash (-) or a dot (.), then the European `d-m-y` format is assumed. – Stanley Umeanozie Jan 25 '19 at 17:32
  • be aware that a value of `$date = "first sat of July 2008";` would be considered a valid date https://www.php.net/manual/en/datetime.formats.php – nulll Sep 26 '22 at 07:15