Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate number of days since start of year with DateTime while accounting for leap years?

I'm trying to use a DateTime object to calculate the current date from the number of days since Jan 1st. Leap years are very important here. Apparently, this does not account for leap years, however.

Here's my code:

$date = DateTime::createFromFormat('z Y', '59 2016');
echo $date->format('n/j/Y')."\n";
die();
like image 589
Dwebtron Avatar asked Feb 03 '15 19:02

Dwebtron


1 Answers

Turns out this is a reported PHP bug from 2012 that I JUST found while I was making this question:

https://bugs.php.net/bug.php?id=62476

That's annoying.

Here is a workaround:

$date = DateTime::createFromFormat('m/d/Y', '01/01/2016');
$date->add(date_interval_create_from_date_string('59 days'));
echo $date->format('m/d/Y')."\n";
like image 158
Dwebtron Avatar answered Nov 06 '22 22:11

Dwebtron