Laravel Excel import returning wrong date

Viewed 1568

I have an Excel file, where I have a date column. The date looks like "17.07.2020".

I'm using Laravel and Maatwebsite Excel import. When I'm saving the imported data to MySQL, the date in MySQL is always "1970-01-01".

Here is the code, which I have now:

return new Product([
    .......
    'discountBeginning'  => date('Y-m-d', strtotime($row['discount_beginning'])
]);

I would like to format the date from Excel to "2020-07-17".

3 Answers

Try this

$date = new DateTime($row['discount_beginning']);
echo $date->format('d.m.Y');

You are using Laravel, so you already have access to the awesome Carbon library. For how data is formatted in your excel file (day.month.year), you can use it like:

return new Product([
    .......
    'discountBeginning'  => \Carbon\Carbon::createFromFormat('d.m.Y', $row['discount_beginning']),
]);

Once you have the carbon instance, you can format it however you would like according to php's date syntax like:

$date = \Carbon\Carbon::createFromFormat('d.m.Y', $row['discount_beginning']);
$date->format('Y-m-d');
$date =  "17.07.2020";
$d2 = \Carbon\Carbon::createFromFormat('d.m.Y', $date)->format('Y-m-d');
dd($d2); // returns: "2020-07-17"

you can also try to append ->toDateString(); if your returned date is not a string. If it is already a string, this will fail.

Related