Error validating date with Carbon?

Asked

Viewed 289 times

0

I’m doing a test and passing an invalid date for a Carbon method.

$data = Carbon::createFromFormat('d/m/Y', '06/17/2010');

As you can see, the method creates from the pattern d/m/y (brazilian standard), thus the date given as argument is invalid as the month value is greater than 12.

I figured some error message would appear, but nothing appears if I try to see what is in the variable $data, a formatted date appears when it is a valid date, works normally.

The result when executing the above code line is:

2011-05-06 16:57:13.0 America/Sao_Paulo (-03:00)

Why this behavior of Carbon?

  • 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.

1 answer

0

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.