通过 Laravel Eloquent 模型在 dd/mm/yyyy 中插入日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48681579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert date format in dd/mm/yyyy through laravel Eloquent Model
提问by Anu Alex
I am using Laravel Eloquent and I have a model with a date field.
我正在使用 Laravel Eloquent 并且我有一个带有日期字段的模型。
My date value is dd/mm/yyyy. The data entered into the system by importing a CSV file. The date value inside the file is in the format dd/mm/yyyy.
我的日期值为dd/mm/yyyy。通过导入 CSV 文件输入系统的数据。文件中的日期值采用dd/mm/yyyy格式。
How can I insert a date with format of dd/mm/yyyy
through the model of laravel eloquent.
如何dd/mm/yyyy
通过laravel eloquent的模型插入格式为日期的日期。
My Model Issue is given below.
我的模型问题如下。
class Issue extends Model
{
protected $table = 'issue';
protected $primaryKey = 'ACC_NO';
protected $keyType = 'String';
public $incrementing = false;
public $timestamps = false;
protected $dates= ['issue_date','due_date'];
public function setIssueDateAttribute($value)
{
$this->attributes['issue_date'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
}
public function setDueDateAttribute($value)
{
$this->attributes['due_date'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
}
}
But still it is not set as in the format of dd/mm/yyyy in mysql database
但是还是没有设置成mysql数据库中的dd/mm/yyyy格式
回答by Alexey Mezenin
You can do this manually with $model->your_date_property = Carbon::parse($someDate)->format('dd/mm/yyyy');
您可以手动执行此操作 $model->your_date_property = Carbon::parse($someDate)->format('dd/mm/yyyy');
Or you can do this automatically. From the docs:
或者您可以自动执行此操作。从文档:
By default, timestamps are formatted as 'Y-m-d H:i:s'. If you need to customize the timestamp format, set the
$dateFormat
property on your model. This property determines how date attributes are stored in the database.
默认情况下,时间戳的格式为“Ymd H:i:s”。如果您需要自定义时间戳格式,请
$dateFormat
在您的模型上设置该属性。此属性确定日期属性在数据库中的存储方式。
protected $dateFormat = 'dd/mm/yyyy';
回答by Prashant Prajapati
It seems you are trying to store or retrieve the date value in specific format the database accept the data in Y-m-d format.i.e(yyyy-mm-dd) I would suggest you to Defining An Accessor for the respective model. E.g
您似乎正在尝试以特定格式存储或检索日期值,数据库接受 Ymd 格式的数据。ie(yyyy-mm-dd) 我建议您为相应模型定义访问器。例如
public function getCreatedAtAttribute($value)
{
$date = Carbon::parse($value);
return $date->format('d-m-Y');
}
Note: use Carbon\Carbon;
注意:使用碳\碳;
use this in your model file before the class begins.
在课程开始之前在您的模型文件中使用它。