首先,我检索所有记录,
//get inventory items
$inv = inventory::all();
然后我循环检索到的记录并修改created_at和updated_at数据以使其更易于人类阅读。
foreach($inv as $i){
$i->created_at = date("M d, Y",strtotime($i->created_at));
$i->updated_at = date("M d, Y",strtotime($i->updated_at));
}
但它返回给我这个错误,
Carbon.php 第 425 行中的 InvalidArgumentException:意外数据 成立。发现意外数据。找不到分隔符号 数据丢失
有什么想法、帮助、线索、建议、推荐吗?
这是我的模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class inventory extends Model
{
protected $table = "inventory";
protected $primaryKey = "item_id";
public $incrementing = false;
public function profile(){
return $this->belongsTo('App\profile','username');
}
public function inventory_images(){
return $this->hasMany('App\inventory_images','item_id');
}
}
在刀片中,我可以使用
{{ date("M d, Y",strtotime($i->created_at)) }}
{{ date("M d, Y",strtotime($i->updated_at)) }}
而且效果很好。
我认为你的处理方式是错误的。数据库中的数据不需要更易于人类阅读,只需显示人类实际
interacts
即可。
为了解决这个问题,我们将创建一个自定义
accessor
方法,该方法将应用于对 created_at
的所有调用。您可以为 updated_at
重新创建此内容。
public function getCreatedAtAttribute($timestamp) {
return Carbon\Carbon::parse($timestamp)->format('M d, Y');
}
然后当您调用
$model->created_at
您的属性将以该格式返回。
如果由于某种原因您绝对需要以该格式存储日期,那么您需要向模型添加一个属性,告诉它
timestamp
列应根据特定类型进行格式化,例如:
protected $dateFormat = 'M d, Y';
旁注
涉及Carbon的原因是它应用于由
$table->timestamps()
生成的所有列,因此created_at
和updated_at
列。protected $dates = []
数组中,这些列也将自动由 Carbon 处理。
这么简单的错误请这样做
检查您的日期格式 (d-m-Y),然后使用相同的格式
$shipDate = Carbon::createFromFormat('d-m-Y H:i',Carbon::parse($request->date)->format('d-m-Y') . " " . $request->time);
我在上传 Excel 时遇到了同样的问题。我尝试了很多解决方案,但没有一个解决方案适合我的情况。经过大量研究后,我找到了解决方案。我希望这个答案对其他人有帮助。
// Convert Excel date to Carbon date
$carbonDate = Carbon::instance(Date::excelToDateTimeObject($row['dob']));
// You can then format the date as needed
$formattedDate = $carbonDate->toDateString(); // 'Y-m-d' format, for example
dd( $row['dob'], $carbonDate, $formattedDate );
输出