Last Updated: February 25, 2016
·
2.416K
· willoller

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