如何格式化 Laravel Excel 中的日期?

How to format dates in Laravel Excel?

我想问一下,我们如何验证 Excel 文件中的日期。我在下面遇到了一些奇怪的测试用例。

首先,我在我的 excel 文件中输入了 5/13/2021,但是当我转储时,它不显示相同,而是显示44329.

但幸运的是,我可以使用以下代码显示到 5/13/2021

$temp = Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
$datetime = Carbon::parse($temp);

所以,我的大问题是无法使用 beforeafter 验证。就像下面的代码一样,它总是失败,但我填写正确。

return Validator::make($rows->toArray(), [
            '*.0' => 'required|after:now|before:0.1' //publish_at
            '*.1' => 'required|before:0.0' // expired_at
        ])->validate();

如下图可以看到,publish_at的值为44329expired_at的值为44330。我不知道为什么会失败。我也试过 gtlt 验证它仍然失败。

有人知道怎么做。将不胜感激。

根据验证,您似乎知道哪些列将是日期。有了这些知识,我相信您可以实施 WithCustomValueBinder 关注,以实现您喜欢的日期格式。

这是一个快速而粗略的示例,用于说明如何将预定义的列数组格式化为日期字符串。根据需要更新列字母和日期格式。显然,您需要添加您首选的导入方法和验证。

<?php

namespace App\Imports;

use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\DefaultValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class SampleImport extends DefaultValueBinder implements WithCustomValueBinder
{
    // set the preferred date format
    private $date_format = 'Y-m-d';

    // set the columns to be formatted as dates
    private $date_columns = ['A','B'];

    // bind date formats to column defined above
    public function bindValue(Cell $cell, $value)
    {
        if (in_array($cell->getColumn(), $this->date_columns)) {
            $cell->setValueExplicit(Date::excelToDateTimeObject($value)->format($this->date_format), DataType::TYPE_STRING);

            return true;
        }

        // else return default behavior
        return parent::bindValue($cell, $value);
    }
}