Which format of date do you use?
You can use this method:
if (Carbon::createFromFormat('YOUR DATE FORMAT', $stringVariable) !== false) {
// valid date
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
How do I check if a string is a valid date using Carbon?
Which format of date do you use?
You can use this method:
if (Carbon::createFromFormat('YOUR DATE FORMAT', $stringVariable) !== false) {
// valid date
}
It throws exception
Maybe try instanciate it and check return value.
Thanks for your answers. I have opted for strtotime($datestring) which returns a boolean. It is short and working.
@richard be careful, because strtotime will return true if someone will send: "now", "next Thursday", "last Monday"... You should correntry handle these cases.
Ok. Thanks
Tried this in tinker
>>> strtotime('2018-02-31')
=> 1520024400
That sucks :(
bool checkdate ( int $month , int $day , int $year ) works
Came here looking for an answer, found my 4 years old answer 🤔
Throw an exception instead of a condition. Carbon will throws one if the string is not a valid date:
use Carbon\Carbon;
use Carbon\Exceptions\InvalidFormatException;
try {
Carbon::parse($timeString);
} catch (InvalidFormatException $e) {
echo 'Failed to parse time string';
}
I find this is a useful function:
/**
* Check if supplied datetime string is a valid date
*/
public static function isValidDate(string $dateString, string $format = 'Y-m-d'): bool
{
$dateTime = CarbonImmutable::createFromFormat($format, $dateString);
return $dateTime && $dateTime->format($format) === $dateString;
}
Please or to participate in this conversation.