Home » excel » How to change excel cell date fromat using PHP

How to change excel cell date fromat using PHP

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to upload data from csv file and my database only accept yyy-mm-dd date format but sometimes users will enter data as dd/mm/yyy date format so I am tried to do following method using Keboola\Csv

if($header[$c]=='date' && $row[$c]!='')
                {
                    $date_text=['--na','--N/'];
                    $sexe_text=str_replace($date_text,'N/A',$row[$c]);
                    if(in_array(array('--na','--N/'),$row))
                    {
                        $newRow[$c]=$sexe_text;
                    }
                    else
                    {

                        $date_array=explode('/', trim($row[$c]));
                        $date=trim($date_array[0]);
                        $month=trim($date_array[1]);
                        $year=trim($date_array[2]);
                        $date_time=$year.'-'.$month.'-'.$date;
                        $newRow[$c]=$date_time;

                    }

                }

But it will revert again if that cell format in dd/mm/yyy so Now I want to change that cell format into date YYY-MM-DD how can I do it using PHP

How to&Answers:

You can direct convert it using date() function.

$exceldate = trim($row[$c]);
$date = date('Y-m-d',strtotime($exceldate));

echo $date;
// 2019-08-09

Answer:

PHP has already predefined date() to convert dates in any format

Simply replace your code with the code given below

if($header[$c]=='date' && $row[$c]!='')
{
    $row[$c] = date('Y-m-d', strtotime($row[$c]));
}
else
{
    # if $row[$c] is null, do whatever you want.
}

The PHP date() accepts date in any format, wheather it is separated by forward slashes or hyphens.
To learn more you can see this documentaion
for date() : https://www.php.net/manual/en/function.date.php
and for strtotime() : https://www.php.net/manual/en/function.strtotime.php