问题描述
我似乎遇到麻烦得到datetime方法按预期工作?我可能会做错事? //通过OK
$ dateTime = DateTime :: createFromFormat('d / m / y','12 / 12/2012');
var_dump($ dateTime);
//应该失败但是返回 - 2016-09-25
$ dateTime = DateTime :: createFromFormat('d / m / Y','56 / 56/2012');
var_dump($ dateTime);
//正确返回False
$ dateTime = DateTime :: createFromFormat('d / m / Y','56 / 56 / fail');
var_dump($ dateTime);
//应该失败但返回2019-08-29 09:58:10
$ dateTime = DateTime :: createFromFormat('m / d / Y','90 / 90/2012 ');
var_dump($ dateTime);
关于 DateTime :: createFromFormat
是有两种类型的意外输入,它识别:产生错误的种类,以及产生警告的种类。
输入如 '56 / 56 / fail'
会产生错误,所以 false
返回,一切都很好。但是, '56 / 56/2012'
不提供错误,而是发出警告,实际上已被解析为2012年第56个月的第56天。自2012年以来没有56个月内,PHP内部更改为2016 + 8个月= 2016年8月。自那个月没有56天之后,我们对2016年9月的+(56 - 31)天= 2016年5月25日再次给予补偿。实际上是正确的。
如果您不想进行此自动调整,您必须将 DateTime
工厂方法并使用作为参考:
$ dateTime = DateTime :: createFromFormat('d / m / Y','56 / 56 / 2012');
$ errors = DateTime :: getLastErrors();
if(!empty($ errors ['warning_count'])){
echo严格来说,该日期无效!\\\
;
}
。
Hi I seem to be having trouble getting the datetime method to work as expected? I may be doing something wrong?
// Passes OK
$dateTime = DateTime::createFromFormat('d/m/Y', '12/12/2012' );
var_dump($dateTime);
// should fail but returns - 2016-09-25
$dateTime = DateTime::createFromFormat('d/m/Y', '56/56/2012' );
var_dump($dateTime);
// correctly returns False
$dateTime = DateTime::createFromFormat('d/m/Y', '56/56/fail' );
var_dump($dateTime);
// should fail but returns 2019-08-29 09:58:10
$dateTime = DateTime::createFromFormat('m/d/Y', '90/90/2012' );
var_dump($dateTime);
The thing about DateTime::createFromFormat
is that there are two kinds of unexpected input it recognizes: the kind that generates errors, and the kind that generates warnings.
Input such as '56/56/fail'
produces an error, so false
is returned and everything is good. However, '56/56/2012'
gives not an error but a warning, and is actually parsed as the 56th day of the 56th month of 2012. Since 2012 does not have 56 months, PHP internally changes this to 2016 + 8 months = Aug 2016. And since that month does not have 56 days, we have another compensation to Sep 2016 + (56 - 31) days = 25 Sep 2016. So while unexpected, this is in fact correct.
If you want to disallow this automatic adjustment, you have to wrap the DateTime
factory method and use DateTime::getLastErrors
as reference:
$dateTime = DateTime::createFromFormat('d/m/Y', '56/56/2012');
$errors = DateTime::getLastErrors();
if (!empty($errors['warning_count'])) {
echo "Strictly speaking, that date was invalid!\n";
}
这篇关于php DateTime createFromFormat功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!