【问题标题】:How to format dates in Laravel Excel?如何在 Laravel Excel 中格式化日期?
【发布时间】:2021-08-09 01:32:56
【问题描述】:

我想问一下,我们如何验证 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 验证它仍然失败。

有人知道怎么做。会很感激的。

【问题讨论】:

    标签: php laravel laravel-validation laravel-excel


    【解决方案1】:

    根据验证,您似乎知道哪些列将是日期。有了这些知识,我相信您可能能够实现 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);
        }
    }
    

    【讨论】:

    • 非常感谢。我通过这个文档修复它,请。接受我的编辑。 docs.laravel-excel.com/3.1/imports/…
    • 很高兴你能成功。有人已经拒绝了编辑,但我根据链接的文档进行了更新。原始代码在我的基本测试中有效,但这次更新是有意义的。
    • np。顺便还看了。这是在这个 doc.link docs.laravel-excel.com/2.1/import/dates.html#format-dates 中格式化日期的另一种方式
    • 这是针对不同版本的 Laravel Excel 吗?我在PHPSpreadSheet docs 中没有看到这些方法。我尝试使用事件将它们应用于阅读器,但它不起作用。我很想知道你是否在 3.x 上工作。
    • 还没试过。只是分享。但我现在可以接受你的回答了。
    猜你喜欢
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多