Tired of dealing with Leap Years? Use DateTime::diff()
Doing this the old-fashioned way was pretty complex. It was bad enough when a normal February would mess up your math, you also had to take leap years into account. Using the DateTime
functions in php >= 5.3
lets you think about your business case, not calendars.
function days_between( $then, $now )
{
// Put the 2 dates into DateTime objects
$then = new DateTime($then);
$now = new DateTime($now);
// Create a DateInterval object using diff() method
$interval = $now->diff($then);
// Format the result as an integer, representing number of days
return $interval->format('%a');
}
Don't take my word for it! Test it!
public function testDaylightSavings()
{
// normal years
$this->assertEquals(0, days_between('2010-01-01', '2010-01-01'));
$this->assertEquals(31, days_between('2010-01-01', '2010-02-01'));
$this->assertEquals(365, days_between('2010-01-01', '2011-01-01'));
$this->assertEquals(365 * 2, days_between('2010-01-01', '2012-01-01'));
// leap year
$this->assertEquals( (365 * 3) + 1, days_between('2010-01-01', '2013-01-01') );
// long times with lots of leap years
$this->assertEquals( (365 * 100) + 24, days_between('1900-01-01', '2000-01-01') );
}
For more info see the php docs: http://php.net/manual/en/datetime.diff.php
Written by Will
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#