如何解决如何在 Laravel Excel 中格式化日期?
我想问一下,我们如何从 Excel 文件中验证日期。我在下面遇到了一些奇怪的测试用例。
首先,我在我的 excel 文件中输入了 5/13/2021,但是当我转储时,它不显示相同,而是显示 44329。
但幸运的是,我可以使用以下代码显示到 5/13/2021:
$temp = Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
$datetime = Carbon::parse($temp);
所以,我的大问题是我不能使用 before
或 after
验证。像下面的代码,它总是失败,即使我正确填写。
return Validator::make($rows->toArray(),[
'*.0' => 'required|after:now|before:0.1' //publish_at
'*.1' => 'required|before:0.0' // expired_at
])->validate();
如下图所示,publish_at
的值为44329,expired_at
的值为44330。我不知道为什么它失败了。我也试过 gt
或 lt
验证它仍然失败。
有人知道怎么做。将不胜感激。
解决方法
根据验证,您似乎知道哪些列将是日期。有了这些知识,我相信您可以实施 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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。