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

Posted

技术标签:

【中文标题】如何在 Laravel Excel 中格式化日期?【英文标题】:How to format dates in 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 验证它仍然失败。

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

【问题讨论】:

【参考方案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 上工作。 还没试过。只是分享。但我现在可以接受你的回答了。

以上是关于如何在 Laravel Excel 中格式化日期?的主要内容,如果未能解决你的问题,请参考以下文章

如何在EXCEL中改变日期格式

如何更改excel中的默认日期格式

在excel中 如何快速吧日期格式ddmmyyyy改为yyyymmdd这种

excel纯数字日期自动如何变成斜杠格式

在EXCEL中如何将日期格式转换,例如把2012/09/01变换成2012-09-01?

在Excel中,如何将数字转化成日期?