【问题标题】:Laravel Excel import returning wrong dateLaravel Excel 导入返回错误日期
【发布时间】:2020-07-17 11:14:12
【问题描述】:

我有一个 Excel 文件,其中有一个日期列。日期看起来像“17.07.2020”。

我正在使用 Laravel 和 Maatwebsite Excel 导入。当我将导入的数据保存到 MySQL 时,MySQL 中的日期始终为“1970-01-01”。

这是我现在拥有的代码:

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

我想将 Excel 中的日期格式化为“2020-07-17”。

【问题讨论】:

  • 我做了一个回答,但再次阅读你的问题。 discountBeginning 是如何存储在您的数据库中的?
  • 为了能够明确回答这个问题,你需要提供$row['discount_beginning']的输出吗?看起来 strtotime() 调用是这里的错误,因为它只是返回 Unix 纪元时间(1970-01-01)。也许$row['discount_beginning']包含strtotime()无法解析的格式?
  • 数据库中的输出始终是“1970-01-01”,即使 Excel 中的日期是 17.07.2020

标签: php laravel


【解决方案1】:

试试这个

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

【讨论】:

  • 鉴于 OPs excel 文件中的格式,我认为这不会起作用。即)6.5.2020 是 5 月 6 日还是 6 月 5 日?
  • 我错了 DateTime 有同样的解释,d.m.Y.
  • 好的,我认为我更新的答案适用于@Jakub Kříž
【解决方案2】:

你正在使用 Laravel,所以你已经可以访问很棒的 Carbon 库了。对于如何在您的 excel 文件(day.month.year)中格式化数据,您可以像这样使用它:

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

一旦你有了 carbon 实例,你可以根据php's date syntax 来格式化它,比如:

$date = \Carbon\Carbon::createFromFormat('d.m.Y', $row['discount_beginning']);
$date->format('Y-m-d');

【讨论】:

  • 我试过你的代码,但它返回一个错误“找不到分隔符号”
  • 我使用 Excel 的默认日期格式,即“17.07.2020”
  • 它甚至不会让我 dd 不知何故。总是同样的错误“找不到分隔符”。
  • 好吧,它看起来像是以通用格式抓取日期,其中 17.07.2020 在 Excel 中看起来像 44029,即使列格式是日期。
  • 是的,日志中的输出是 44029。它是 Excel 中的一种格式,例如时间、货币、日期、百分比等。bettersolutions.com/excel/formatting/…
【解决方案3】:
$date =  "17.07.2020";
$d2 = \Carbon\Carbon::createFromFormat('d.m.Y', $date)->format('Y-m-d');
dd($d2); // returns: "2020-07-17"

如果您返回的日期不是字符串,您也可以尝试附加->toDateString();。如果它已经是一个字符串,这将失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2018-09-25
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    相关资源
    最近更新 更多