【问题标题】:Laravel Carbon failed to parse time string errorLaravel Carbon 无法解析时间字符串错误
【发布时间】:2021-08-27 10:29:01
【问题描述】:

我使用 excel maatwebsite laravel 将数据从 excel 导入到 mysql 数据库,我不知道为什么,但我看到 Excel 中的日期列是文本格式(只有当我在每个单元格中单击 ENTER 时,它才会变成日期格式), 所以我发现的唯一自动导入它们的方法是

 public function model(array $row)
    {
        $year_pd = Carbon::parse($row[7])->format("Y");
        $day_pd = Carbon::parse($row[7])->format("m");
        $month_pd = Carbon::parse($row[7])->format("d");
        $hour_pd = Carbon::parse($row[7])->format("H");
        $minute_pd = Carbon::parse($row[7])->format("i");
        $pickup_date = Carbon::create($year_pd, $month_pd, $day_pd, $hour_pd, $minute_pd);
        $year_dd = Carbon::parse($row[8])->format("Y");
        $day_dd = Carbon::parse($row[8])->format("m");
        $month_dd = Carbon::parse($row[8])->format("d");
        $hour_dd = Carbon::parse($row[8])->format("H");
        $minute_dd = Carbon::parse($row[8])->format("i");
        $drop_date = Carbon::create($year_dd, $month_dd, $day_dd, $hour_dd, $minute_dd);

        return new Driveme([
              'targa' => $row[14],
              'modello' => $row[13],
              'driver' => $row[10],
              'pickup_date' => $pickup_date,
              'drop_date' => $drop_date,
          
              //'pickup_date' => Carbon::createFromFormat($row[7]),
              //'drop_date' => Carbon::createFromFormat($row[8]),
          ]);

但在某些时候导入停止,它给了我这个错误

无法解析“13/06/2021 19:00”: DateTime::__construct():无法在位置 0 (1) 解析时间字符串 (13/06/2021 19:00):意外字符

所有日期都具有相同的格式,那么如果它们都相似,为什么它会随便停在一个日期上呢?

如果我使用 Carbon::createFromFormat($row[7]) 它告诉我格式日期不正确

谢谢

【问题讨论】:

  • 13/06/2021 不是有效格式。 Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.。它试图将其解析为m/d/y,并且没有 13 个月。尝试使用createFromFormat 而不是parse

标签: php excel laravel


【解决方案1】:

正如我提到的,13/06/2021 被解析为 m/d/Y,这是由于 PHP strtotime rules。其他日期可能会出现,因为第一个数字在 1-12 之间,但您不会得到您想要的实际日期(您发送 01/06/2021 预计 6 月 1 日,但 Carbon 将返回 1 月 6 日))。您需要将格式传递给 createFromFormat 函数:

 Carbon::createFromFormat('d/m/Y H:i', $row[7]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-08
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多