When using this command it needs to be checked if there has been an error with the method getLastErrors()
that by that date informed 06/17/2010
has the following result:
>>> $data = \Carbon\Carbon::createFromFormat('d/m/Y', '06/17/2010');
=> Carbon\Carbon {#1031
+"date": "2011-05-06 00:46:30.000000",
+"timezone_type": 3,
+"timezone": "America/Sao_Paulo",
}
>>> \Carbon\Carbon::getLastErrors()
=> [
"warning_count" => 1,
"warnings" => [
10 => "The parsed date was invalid",
],
"error_count" => 0,
"errors" => [],
]
>>>
then, in addition to using the method createFromFormat
, right after you need to call the method getLastErrors()
and with its array
of checking information warning_count
and error_count
if they are equal to zero, if they are not have problems in date.
Sample code:
$data = Carbon::createFromFormat('d/m/Y', '06/17/2010');
$error = Carbon::getLastErrors();
if ($error['error_count'] === 0 && $error['warning_count'] === 0)
{
//data válida
}
else
{
//data inválida
}
It is also worth remembering that the Carbon class inherits class behaviors Datetime which has the same method Datetime::createFromFormat, which explains the problems and errors encountered in a date by the same method Datetime::getLastErrors().
If you only want to check if the date is valid you can use the function date_parse_from_format as follows:
$errors = date_parse_from_format('d/m/Y','06/17/2010')
which returns virtually the same information as the method getLastErrors()
, example:
=> [
"year" => 2010,
"month" => 17,
"day" => 6,
"hour" => false,
"minute" => false,
"second" => false,
"fraction" => false,
"warning_count" => 1,
"warnings" => [
10 => "The parsed date was invalid",
],
"error_count" => 0,
"errors" => [],
"is_localtime" => false,
]
ie, check error_count
and warning_count
if both are of the value 0 to date is valid, if it’s bigger than 0 any one to date is not valid.
I believe that Carbon does not serve to be able to validate dates, you do not think you better treat this before you check the data? You can use the
Validator
from Laravel himself to help you.– Ricardo Lucas