PHP DateTime :: createFromFormat行为 [英] PHP DateTime::createFromFormat behavoiur

查看:84
本文介绍了PHP DateTime :: createFromFormat行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我对 \DateTime :: createFromFormat 函数的行为感到困惑。

Today I've encountered something confusing for me with the behaviour of the \DateTime::createFromFormat function.

就我而言,我有一个字符串,以以下格式表示日期: m / Y(05/2017)。当我想将字符串转换为DateTime对象时,遇到以下问题:

In my case I have a string, representing the date in the following format m/Y (05/2017). When I want to convert the string to DateTime object I've encountered the following issue:

$ date = \DateTime :: createFromFormat(' m / Y','02 / 2017');

当我转储 $ date 变量,其中的date属性为'2017-03-03 11:06:36.000000'

When I dump the $date variable, the date property inside is '2017-03-03 11:06:36.000000'

但是如果我在月份之前添加日期 $ date = \DateTime :: createFromFormat('d / m / Y','01 / 02/2017'); 我获取具有正确日期属性的对象。 (不幸的是,我无法更改日期格式并添加日期。日期必须是m / Y。)

But if I add the date before the month $date = \DateTime::createFromFormat('d/m/Y', '01/02/2017'); I get back an object with correct date property. (unfortunately I cant change the format of the date and add the day. It must be m/Y).

我想出的解决方法是将日期字符串的月份的第一天,我有 $ date = '01 /'.$ dateString; ,但是我宁愿不这样做,因为它是硬编码的。

The fix I've come up with is to concatenate the first day of the month to the date string I have $date = '01/'.$dateString; but I rather not to do that because it's hardcoded.

这是怎么了? createFromFormat函数是否缺少有关如何创建对象的信息?我对此很困惑。

What is wrong here? Does the createFromFormat function lack information of how to create the object? I'm quite confused with this. Thanks for everyone's help in advance!

推荐答案

默认情况下,PHP将使用当前日期/时间的值填充缺少的日期值;因此

By default, PHP will populate missing date values with those of the current date/time; so

$date = \DateTime::createFromFormat('m/Y', '02/2017');

将使用当前日期填充缺少的日期值;由于2月31日为无效日期,因此它将向前滚动到3月。同样,小时/分钟/秒将根据当前时间填充缺少的时间值。

will populate the missing day value with the current date; and as 31st February is an invalid date, it will roll forward into March. Likewise, hours/minutes/seconds will be populated with the missing time values based on the current time.

如果要强制将强制行为设置为开始时,月/时间,然后用前导

If you want to force the behaviour of forcing to the beginning of the month/time, then modify your mask with a leading !

$date = \DateTime::createFromFormat('!m/Y', '02/2017');

这将在月份的第一天填充丢失的日期,在<$ c $填充时间c> 00:00:00

This will populate the missing day with the 1st of the month, and the time with 00:00:00

或者,结尾的 | 将具有相同效果

Alternatively, a trailing | will have the same effect

$date = \DateTime::createFromFormat('m/Y|', '02/2017');

这篇关于PHP DateTime :: createFromFormat行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆