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,231
  • 3
  • 19
  • 36

1 Answers1

0
$timestamp  = strtotime($date);

return $timestamp ? $date  : null ;
Funk Forty Niner
  • 74,372
  • 15
  • 66
  • 132
  • 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