I am having a CSV to be prone to errors (typed by hand) to import to Oracle.
I want to check if the field in it is a valid (dd/mm/yyyy) date.
I wrote the following code
function check_date($a1,$a2,$a3,$a4)
{
global $error;
if ( DateTime::createFromFormat('d/m/Y', $a1)->format('d/m/Y') !== $a1 )
{
echo "ERROR - Row ($a2) - Column ($a4) - Invalid $a3</br>";
$error = 1 ;
}
}
This failed if the field was empty so I added to be
function check_date($a1,$a2,$a3,$a4)
{
global $error;
if ( $a1 == "" )
{
echo "ERROR - Row ($a2) - Column ($a4) - Empty $a3</br>";
$error = 1 ;
goto end_function ;
}
if ( DateTime::createFromFormat('d/m/Y', $a1)->format('d/m/Y') !== $a1 )
{
echo "ERROR - Row ($a2) - Column ($a4) - Invalid $a3</br>";
$error = 1 ;
}
end_function:
}
Now the problem is if the field is any character like 'a' the script fails.
I call the function
check_date($CSVData[2], $row_count, "ISSUE_DATE" , $alphabet[2] ) ;
How can I solve it.
Thanks.
You just need to check if the result of
DateTime::createFromFormatis aDateTimeobject before attempting to use it. Since it's now (as of PHP8.0.21, 8.1.8 and 8.2.0) possible for this function to throw an error, this can be implemented with a try/catch block, throwing an exception if the conversion fails or doesn't match the input:Output:
Demo on 3v4l.org