简体   繁体   中英

How to check string on date in laravel?

How to check string on date in laravel?

I want to handle the situation if string doesn't date for example like "it's some not date string".

I try it code, but it doesn't work I have next error:

InvalidArgumentException  : A two digit month could not be found
Data missing

My code:

    if (Carbon::createFromFormat('m-d-Y', $rowMatrix[4]) !== false) {
//
}

You can use try/catch block :

try {
    $date = Carbon::createFromFormat('m-d-Y', $rowMatrix[4])
} catch(InvalidArgumentException $e) {
    $date = 'Not a date';
}

But a much better way is to use Laravel validation date_format rule to make sure the string is a date:

'some_date_field' => 'date_format:"m-d-Y"',

You can use DateTime for this purpose :

$dateTime = DateTime::createFromFormat('d/m/Y', $rowMatrix[4]);
$errors = DateTime::getLastErrors();
if (!empty($errors['warning_count'])) {
    // Not a date
}

Or you can check it like this :

if (date('Y-m-d H:i:s', strtotime($rowMatrix[4])) == $rowMatrix[4]){
    // it's a date
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM