Using DateInterval class in PHP

DateInterval is (amongst others) a relatively new addition to the date extension in PHP 5.3. It allows to describe an interval in time, and you can perform actions with that interval. Basically, it allows to calculate with dates in a very easy way, and do even more fun stuff with it.

Unfortunately no documentation exists today for DateInterval and friends, but PHP is open-source so you can easily have a peek at the code to see what’s happening under the engine. This is more or less what the documentation for DateInterval and some helper functions could look like:

Prototype:

DateInterval DateInterval::__construct (string $interval)

Creates a DateInterval instance, based on the interval provided.

Parameters:
- $interval: ISO 8601 style time interval notation. (see Wikipedia)

Return Values:
Returns DateInterval object on success or FALSE on failure.

Example:

// Interval. This acutally means 3 years, 6 months, 
// 4 days, 12 hours, 30 minutes and 5 seconds.
$interval = 'P3Y6M4DT12H30M5S';
$i = new DateInterval( $interval );

This alone isn’t very exciting, but the fun stuff begins if you use some extra date functions with it:

// let's assume $i is still around from the previous example
$format = 'Y-m-d H:i:s';
$d = new DateTime('2008-01-01 12:25');
date_add( $d, $i );
echo $d->format( $format ) . PHP_EOL;
date_sub( $d, $i );
echo $d->format( $format ) . PHP_EOL;
 
$d2 = new DateTime('2008-01-01 12:25');
$diff = date_diff( $d, $d2 );
date_sub( $d2, $diff );
echo $d2->format( $format ) . PHP_EOL;

There’s a lot more possible (have a look at the DatePeriod class too), but that’s for another time. This is a pretty new group of classes within PHP, so expect these to expand in functionality in the future.

4 Responses to “Using DateInterval class in PHP”


  • Nice to find some information on these classes!

    They are really hard to work with right now, not only because of the lack of docs.

    For example in my app I have an interval calculated in seconds, that I need to add to a DateTime object. But I can’t create a DateInterval from seconds, I have to split those seconds into minutes, hours, days etc to form a valid interval string. Ouch.

    I hope they continue to evolve.

  • Scrap that comment, it works fine.

    $finished->add(new DateInterval(‘PT’.$secondsToGo.’S'));

  • Thanks for the helpful article. It got me unstuck (for now, anyway :) ).

    Here’s an simple example of using DateTime, DateInterval, and DatePeriod together:

    $dt = new DateTime();
    $interval = new DateInterval(‘P1M’);
    $period = new DatePeriod($dt, $interval, 12);
    foreach ($period as $each) {
    echo $each->format(‘Y-m-d’) . ”;
    }

  • Thanks for the article, and thanks pcguru for the comment. I couldn’t work out how to add hours but now I see
    $d->add(new DateInterval(‘PT2H’));

    :D

Leave a Reply