Reputation: 51
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".
Upvotes: 4
Views: 4904
Reputation: 1906
Try this. it will work sure. I tested with my code but note that the imported file should be in CSV format...
Carbon::createFromFormat('d/m/Y', $row['discount_beginning'])->format('Y-m-d')
Upvotes: 0
Reputation: 6551
$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.
Upvotes: 0
Reputation: 6005
Try this
$date = new DateTime($row['discount_beginning']);
echo $date->format('d.m.Y');
Upvotes: 3
Reputation: 3764
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');
Upvotes: 0