Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

richard's avatar

How To Check is a string is a valid date

How do I check if a string is a valid date using Carbon?

0 likes
13 replies
gregurco's avatar

Which format of date do you use?

You can use this method:

if (Carbon::createFromFormat('YOUR DATE FORMAT', $stringVariable) !== false) {
    // valid date
}
7 likes
bestmomo's avatar

Maybe try instanciate it and check return value.

richard's avatar

Thanks for your answers. I have opted for strtotime($datestring) which returns a boolean. It is short and working.

2 likes
gregurco's avatar

@richard be careful, because strtotime will return true if someone will send: "now", "next Thursday", "last Monday"... You should correntry handle these cases.

2 likes
andreich1980's avatar

Tried this in tinker

>>> strtotime('2018-02-31')
=> 1520024400

That sucks :(

andreich1980's avatar

bool checkdate ( int $month , int $day , int $year ) works

2 likes
andreich1980's avatar

Came here looking for an answer, found my 4 years old answer 🤔

7 likes
EveAT's avatar

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';
}
1 like
MrMoto9000's avatar

@Snapey It's still the number one result on Google, so why open another question? Don't really understand the need for sarcastic remarks from forum elders. It's unhelpful and makes the forum unwelcoming.

2 likes
MrMoto9000's avatar

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;
    }
1 like

Please or to participate in this conversation.