Ahora

An improved API for working with date intervals.

composer require savvywombat\ahora
Latest Version on Packagist Supported PHP Version MIT License

What exactly does Ahora solve?

The built-in PHP DateInterval API is useful, but limited, especially when trying to perform any kind of mathematic operation (such as adding or subtracting intervals). Other libraries extend on DateInterval, which means they suffer the same limitations.

Ahora provides a new API that does not extend the PHP DateInterval (although it provides methods to allow easy conversion), so it has more freedom to overcome the limitations.

Consider the following:

$interval = new DateInterval("PT150S"); // create an interval of 150 seconds

echo $interval->i . " minutes\n"; // 0 minutes
echo $interval->s . " seconds\n"; // 150 seconds


$interval = new DateInterval("PT2M30S"); // create an interval of 2 minutes and 30 seconds

echo $interval->i . " minutes\n"; // 2 minutes
echo $interval->s . " seconds\n"; // 30 seconds

Sensibly, 150 seconds should be the equivalent of 2 minutes and 30 seconds, but PHP DateInterval treats them differently.

Moreover, there is no simple way to add or substract time from a PHP DateInterval, or to format it.

Ahora solves these challenges by providing interval equivalence.

Interval equivalence

use SavvyWombat\Ahora\Interval;

$interval = new Interval("PT150S"); // create an interval of 150 seconds
echo $interval->minutes . " minutes\n"; // 2 minutes
echo $interval->seconds . " seconds\n"; // 30 seconds
echo $interval->realSeconds . " seconds\n"; // 150 seconds

$interval = new Interval("PT2M30S"); // create an interval of 2 minutes and 30 seconds (equivalent of 150 seconds)
echo $interval->minutes . " minutes\n"; // 2 minutes
echo $interval->seconds . " seconds\n"; // 30 seconds
echo $interval->realSeconds . " seconds\n"; // 150 seconds

Interval mathematics

With Ahora, it is possible to add or subtract one interval from another.

use SavvyWombat\Ahora\Interval;

$interval = new Interval("PT25S"); // create an interval of 25 seconds
$interval->addInterval(new Interval("PT170S")); // add an interval of 170 seconds

echo $interval->seconds; // outputs 15
echo $interval->minutes; // outputs 3

echo $interval->realSeconds; // outputs 195

$interval->subtractInterval(new Interval("PT2M")); // subtract an interval of 2 minutes (120 seconds)
echo $interval->seconds; // outputs 15
echo $interval->minutes; // outputs 1

echo $interval->realSeconds; // outputs 75