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.