编程语言
首页 > 编程语言> > PHP CreateFromFromFormat()仅月份和年份

PHP CreateFromFromFormat()仅月份和年份

作者:互联网

这个问题已经在这里有了答案:            >            date_create_from_format() returns wrong value.                                     1个
我正在尝试使用Datetime Class从格式创建数据,如下所示

$date = DateTime::createFromFormat('m-Y', '02-2016');
echo $date->format('Y-m-d');

放出2016-03-01,我期望得到2016-02-01

是虫子吗?还是我以错误的方式低估了此功能?

解决方法:

如果提供月份和年份,则PHP将使用今天当前月份的当前日期(即30)提供默认日期

这样会产生一个有效的2016-02-30,这不是一个有效的日期…..但是PHP允许这些类型的值,其中天数高于/低于月份中的天数,月数高于/低于年份中的月数. ,并且仅递增/递减到有效日期…..在这种情况下,是在第2个月或2016年的最后一天(2016年2月29日)之后再增加1天,以给出2016年3月1日

编辑

Reference for day/month overflow/underflow behaviour

Note:
It is possible to over- and underflow the dd and DD format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes “2008-08-00” equivalent to “2008-07-31” and “2008-06-31” equivalent to “2008-07-01” (June only has 30 days).
It is also possible to underflow the mm and MM formats with the value 0. A month value of 0 means December of the previous year. As example “2008-00-22” is equivalent to “2007-12-22”.
If you combine the previous two facts and underflow both the day and the month, the following happens: “2008-00-00” first gets converted to “2007-12-00” which then gets converted to “2007-11-30”. This also happens with the string “0000-00-00”, which gets transformed into “-0001-11-30” (the year -1 in the ISO 8601 calendar, which is 2 BC in the proleptic Gregorian calendar).

标签:date-format,datetime-format,time-format,datetime,php
来源: https://codeday.me/bug/20191118/2031476.html