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

phpMick's avatar
Level 15

Check date is valid.

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
}
0 likes
3 replies
lostdreamer_nl's avatar

you'll have to check some formats yourself i'm afraid. but it's actually for the best: as US formats differ from others you can sometimes get Y-m-d or d-m-Y or m-d-Y

Having a date like 08-07-18 could be Aug 7, or Jul 8

I usually do something like:

public function setDateAttribute($date)
{
    $approvedFormats = [ 'Y-m-d', 'd-m-Y', 'y-m-d', 'd-m-y', 'd M Y'];
    foreach($approvedFormats as $format) {
        if($carbon = Carbon::createFromFormat($format, $date)) {
            $this->attributes['date'] = $carbon->format('Y-m-d');
        }
    }
}

Checking a few formats to see what the client inputted this time, and reformatting it to Y-m-d before saving to the model.

1 like
phpMick's avatar
Level 15

This is how I eventually did it:

/**
 * Use the Laravel validation to validate a value.
 *
 * @param $value the value to test
 * @param $rules Laravel standard rules: 'required|numeric'
 * @return bool
 */
function validateValue($value,$rules)
{

    //needs to be an assoc
    $assoc = ['value'=>$value];

    $validator = Validator::make($assoc, [
        'value' => $rules,
    ]);

    return !$validator->fails();


}

Figured I should just use the Laravel code. Genius or lunacy?

Mick

mattesbarbosa's avatar

strtotime will return a number below zero when the date is invalid such as common in MySQL 0000-00-00 00:00:00. Make sure you pass an object type date or carbon:

return strtotime(date or carbon object) < 0 ? null : date

2 likes

Please or to participate in this conversation.