PHP的DateTime :: createFromFormat忽略leap年 [英] PHP's DateTime::createFromFormat ignores leap years
问题描述
我必须在日期中转换DayOfYear值。
I have to convert a DayOfYear-value in a Date.
我尝试在2016年第70天进行跟踪:
I tried following for the 70th day of 2016:
php -r 'var_dump(DateTime::createFromFormat("z Y","69 2016"));'
class DateTime#1 (3) {
public $date =>
string(26) "2016-03-11 14:21:07.000000"
public $timezone_type =>
int(3)
public $timezone =>
string(3) "UTC"
}
( z是基于null的)
('z' is null-based)
但这是错误的。应该是2016年3月10日!
But that's wrong. It should be the 2016-03-10!
这是PHP错误吗?
推荐答案
它看起来像个错误。 (正如@aioros在评论中所说,它是错误#62476 。)
It looks like a bug. (As @aioros remarks in a comment, it's bug #62476.)
但是,如果您在一年的第一天创建 DateTime
对象,然后添加数字,则可以绕开它需要的天数:
You can, however, circumvent it if you create the DateTime
object for the first day of the year then add the number of days you need:
$date =
DateTime::createFromFormat("z Y","0 2016", new DateTimeZone("UTC"))
->add(new DateInterval("P69D"))
;
var_dump($date);
它显示:
class DateTime#2 (3) {
public $date =>
string(26) "2016-03-10 14:46:37.000000"
public $timezone_type =>
int(3)
public $timezone =>
string(3) "UTC"
}
更新:
另一种解决方法,在对 PHP错误#62476 是将年份放在第一位:
Another workaround, suggested in a comment on PHP bug #62476 is to put the year first:
DateTime::createFromFormat("Y z","2016 69");
这样可以正常工作。
这篇关于PHP的DateTime :: createFromFormat忽略leap年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!