[英]Laravel date_format field validation backwards?
I'm trying to determine where the issue is here. 我正在尝试确定问题出在哪里。 I'm taking an input of something like "01-02-2018" to refer to January 02, 2018. Then creating a variable to fix it as a standard 2018-01-02 DATE formate for mySQL and saving it.
我正在输入类似“ 01-02-2018”之类的内容来引用2018年1月2日。然后创建一个变量以将其固定为mySQL的标准2018-01-02 DATE格式,并保存它。 However, when it saves, it is saving it as 2018-02-01, transposing the month and day, which represents February 01, 2018. Here is what my code looks like:
但是,保存时,将其保存为2018-02-01,将月份和日期进行转置,代表2018年2月1日。这是我的代码:
Validation 验证方式
'prescribe_date' => 'nullable|date_format:"m-d-Y"|max:10',
Fix 固定
$prescribe_dateFix = date('Y-m-d', strtotime($request->prescribe_date));
Save 救
$prescription->prescribe_date = $prescribe_dateFix;
strtotime
will interpret your date as dmY
by default so it will think it is 1st February. 默认情况下,
strtotime
会将您的日期解释为dmY
,因此它将认为是2月1日。 From the manual: 从手册中:
Note:
注意:
Dates in the m/d/y or dmy formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed;
通过查看各个组成部分之间的分隔符,可以消除m / d / y或dmy格式的日期的歧义:如果分隔符为斜杠(/),则假定为美国m / d / y; whereas if the separator is a dash (-) or a dot (.), then the European dmy format is assumed.
相反,如果分隔符是破折号(-)或点(。),则采用欧洲dmy格式。
You need to use date_create_from_format
instead: 您需要改用
date_create_from_format
:
$request = (object)['prescribe_date' => '01-02-2018'];
$prescribe_dateFix = date_create_from_format('m-d-Y', $request->prescribe_date)->format('Y-m-d');
echo $prescribe_dateFix;
Output: 输出:
2018-01-02
你可以试试看
$prescribe_dateFix = date_format($request->prescribe_date, 'Y-m-d')
The "Laravelish" way of achieving this is using the built-in Carbon library for smart PHP date manipulation: 实现这一目标的“粗略”方法是使用内置的Carbon库进行智能PHP日期操作:
// Perform validation and then...
$prescription->prescribe_date = Carbon::createFromFormat('m-d-Y', $request->prescribe_date);
$prescription->save();
Of course, you should also specify that the prescribe_date
field is a date within the corresponding model class (see https://laravel.com/docs/5.7/eloquent-mutators#date-mutators ): 当然,您还应该指定
prescribe_date
字段是相应模型类中的日期(请参阅https://laravel.com/docs/5.7/eloquent-mutators#date-mutators ):
In Prescription
model class: 在“
Prescription
模型类中:
protected $dates = [
'created_at',
'updated_at',
'prescribe_date'
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.