Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's DateTime::createFromFormat ignores leap years

Tags:

date

php

I have to convert a DayOfYear-value in a Date.

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' is null-based)

But that's wrong. It should be the 2016-03-10!

Is it a PHP-Bug?

like image 424
Andreas Pohl Avatar asked Feb 22 '16 14:02

Andreas Pohl


1 Answers

It looks like a bug. (As @aioros remarks in a comment, it's bug #62476.)

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);

It displays:

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"
}

Update:

Another workaround, suggested in a comment on PHP bug #62476 is to put the year first:

DateTime::createFromFormat("Y z","2016 69");

This way it works as expected.

like image 68
axiac Avatar answered Nov 18 '22 02:11

axiac