Skip to content
thesis-phpPublic

About

Time\Duration polyfill for PHP >=8.2, shorthands like sec(5) and toMs(), strings like 1h30m, PSR-20 clocks.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

57 Commits

Folders and files

Repository files navigation

Thesis Time

PHP Release License PHPStan Coverage Mutation score

A read-only split of packages/time from the thesis-php/thesis monorepo: issues and pull requests go there.

Report a bug · Request a feature · Changelog · Contributing

A polyfill of Time\Duration of PHP 8.6 for PHP 8.2 to 8.5, short functions for it and PSR-20 clocks.

use function Thesis\Time\{formatDuration, parseDuration, sec, toMs, toSecFloat};

$timeout = sec(1.5);

toMs($timeout, RoundingMode::PositiveInfinity); // 1500
toSecFloat($timeout); // 1.5
formatDuration($timeout); // 1.5s

$timeout = parseDuration($_ENV['HTTP_TIMEOUT'] ?? '1.5s');

Installation

composer require thesis/time

Requires PHP 8.2.2+, 64-bit or 32-bit. No extensions. Below PHP 8.4 \RoundingMode comes from symfony/polyfill-php84.

Time\Duration polyfill

Time\Duration is elapsed time with nanosecond precision: a timeout, a delay, a TTL. On PHP 8.2 to 8.5 the package declares Time\Duration and Time\TimeException, on PHP 8.6 the built-in classes work, so code written for 8.6 runs on 8.2 as is. Here are the essentials, the RFC describes the whole class.

use Time\Duration;

$ttl = Duration::fromMinutes(5);
$timeout = Duration::fromSeconds(1, nanoseconds: 500_000_000);
$delay = Duration::fromIso8601DurationString('PT1M30S');

$ttl->add($timeout);
$ttl->sub($timeout);
$timeout->multiplyBy(3);
$timeout->divideBy(2);
$timeout->negate();
$timeout->absolute();

Duration::compare($ttl, $timeout); // 1
$timeout < $ttl; // true

$timeout->seconds; // 1
$timeout->nanoseconds; // 500000000
$timeout->negative; // false

The factories are fromNanoseconds(), fromMicroseconds(), fromMilliseconds(), fromSeconds(), fromMinutes() and fromHours(). The class is minimal on purpose: the factories take only non-negative ints, and nothing converts a duration back to a number. The functions fill these gaps.

A duration spans about ±292 years, ±68 years on 32-bit PHP. A value out of range throws Time\TimeException.

The polyfill behaves as the class of PHP 8.6 down to the exception messages, compared with the original on random input. What differs: var_dump() and an (array) cast show two more private properties, reflection sees __serialize(), and a wrong call fails as with a userland method (extra arguments are ignored, null for an int is a TypeError in coercive mode too).

Functions

Creating

Unlike the factories of the class, the functions take a negative value, and all but ns() a float, rounded to the nearest nanosecond, half away from zero.

use function Thesis\Time\{duration, hours, minutes, ms, ns, sec, us};

ns(15);
us(1.5);
ms(-250);
sec(90);
minutes(1.5);
hours(0.25);

duration(minutes: 1, sec: 30); // the sum of the parts

A value out of range throws Time\TimeException, NAN and INF throw \ValueError.

Converting to int

use function Thesis\Time\{sec, toHours, toMinutes, toMs, toNs, toSec, toUs};

$duration = sec(90.5);

toNs($duration);                                    // 90500000000
toUs($duration, RoundingMode::TowardsZero);         // 90500000
toMs($duration, RoundingMode::TowardsZero);         // 90500
toSec($duration, RoundingMode::TowardsZero);        // 90
toSec($duration, RoundingMode::PositiveInfinity);   // 91
toMinutes($duration, RoundingMode::TowardsZero);    // 1
toHours($duration, RoundingMode::PositiveInfinity); // 1

toNs() is exact. The others take a \RoundingMode and have no default: the right one depends on what the number means. Round a timeout, a TTL or an interval up with PositiveInfinity, so that it never expires early and a positive one never becomes the 0 that many APIs take as "no limit", see the table below. A deadline that has passed still gives 0 or less: take max(1, ...) or check it with $remaining > sec(0) first. Drop the fraction of elapsed time with TowardsZero.

On 64-bit PHP every duration fits in an int of any unit, nanoseconds too. On 32-bit PHP an int holds 2.1 seconds of nanoseconds, 35 minutes of microseconds, 24 days of milliseconds, and a larger result throws Time\TimeException. The float conversions never throw.

Converting to float

use function Thesis\Time\{sec, toHoursFloat, toMinutesFloat, toMsFloat, toNsFloat, toSecFloat, toUsFloat};

$duration = sec(90.5);

toNsFloat($duration);      // 90500000000.0
toUsFloat($duration);      // 90500000.0
toMsFloat($duration);      // 90500.0
toSecFloat($duration);     // 90.5
toMinutesFloat($duration); // 1.5083333333333333
toHoursFloat($duration);   // 0.025138888888888888

For APIs that take float seconds, like the timeout of stream_socket_client(), and for metrics and logs. The result is the float nearest to the duration up to 104 days (2^53 nanoseconds), and at most a unit in the last place off above. toNsFloat() is for 32-bit PHP, where toNs() throws.

Passing to other APIs

What to pass where a timeout or a TTL is a number, and what 0 means there: rarely "at once".

Where Pass 0 means
curl, CURLOPT_TIMEOUT_MS toMs($timeout, RoundingMode::PositiveInfinity) no limit
curl, CURLOPT_CONNECTTIMEOUT_MS toMs($timeout, RoundingMode::PositiveInfinity) the default, 300 seconds
Guzzle, timeout toSecFloat($timeout) no limit
Guzzle, connect_timeout toSecFloat($timeout) 300 seconds
Symfony HttpClient, max_duration toSecFloat($timeout) no limit
Symfony HttpClient, timeout toSecFloat($timeout) times out at once
PDO, PDO::ATTR_TIMEOUT toSec($timeout, RoundingMode::PositiveInfinity) no limit, not in SQLite
stream_set_timeout() toUs($timeout, RoundingMode::PositiveInfinity) a read does not wait
PSR-16, $ttl toSec($ttl, RoundingMode::PositiveInfinity) the item is deleted
Postgres, statement_timeout toMs($timeout, RoundingMode::PositiveInfinity) no limit
  • curl. CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT take whole seconds: toSec() with the same mode.
  • Guzzle, Symfony HttpClient. Float seconds need no mode, but with curl both turn them into whole milliseconds and drop the fraction: 0.9 ms becomes 0, no limit. Where a timeout can be that short (the time left until a deadline), pass max(0.001, toSecFloat($timeout)). timeout of Symfony limits the wait between two chunks, the whole request is limited by max_duration.
  • PDO. The time to connect in MySQL and Postgres, where 0 waits as long as the system does. In SQLite the wait for a locked database, where 0 fails at once.
  • stream_set_timeout(). The microseconds, with 0 seconds before them: PHP carries whole seconds over, stream_set_timeout($stream, 0, toUs($timeout, RoundingMode::PositiveInfinity)). No limit is -1 second.
  • PSR-16. A negative TTL deletes the item too, null is the default TTL of the cache.
  • Postgres. A number without a unit is milliseconds, also in lock_timeout and idle_in_transaction_session_timeout.

Checking, comparing, multiplying, dividing

use function Thesis\Time\{isZero, multiply, ratio, sec};

isZero($duration);
$duration->negative;
$duration > sec(0);
$elapsed >= $timeout;

min($a, $b, $c);
max($a, $b, $c);

multiply($delay, 2); // exact
multiply($delay, 1.5); // rounded to the nearest nanosecond
multiply($delay, -1);

ratio($elapsed, $total); // 0.25, a progress
ratio($cpuTime, $elapsed); // 0.8, a load
(int) ratio($elapsed, $interval); // the intervals that have passed

<, <=, >, >= and <=> compare durations by value, on PHP 8.6 and with the polyfill, and so do min(), max() and sort() of PHP. Check zero with isZero(), not with ==: PHP CS Fixer and others make it ===, which compares the objects.

ratio() divides a duration by a duration, which the class does not. The result is the float nearest to the quotient while both are up to 104 days, so durations that divide evenly give a whole number. A zero divisor throws \DivisionByZeroError.

Rounding

use function Thesis\Time\{formatDuration, minutes, ms, roundDurationTo};

formatDuration($elapsed); // 1.234567891s
formatDuration(roundDurationTo($elapsed, ms(1), RoundingMode::HalfAwayFromZero)); // 1.235s

roundDurationTo($timeout, minutes(1), RoundingMode::PositiveInfinity);

roundDurationTo() rounds a duration to a multiple of a unit, like Duration.Round() and Duration.Truncate() of Go. The unit is any positive duration, ms(1500) too, anything else throws \ValueError. The \RoundingMode has no default, as in the conversions to int.

Formatting and parsing

formatDuration() writes a duration like Duration.String() of Go, and parseDuration() reads it back in the grammar of time.ParseDuration(): for logs, and for a timeout in an environment variable, a config or an option of a command.

use function Thesis\Time\{duration, formatDuration, parseDuration};

formatDuration(duration(hours: 1, minutes: 2, sec: 3.5)); // 1h2m3.5s
formatDuration(parseDuration('90s')); // 1m30s

parseDuration('1h2m3.5s');
parseDuration('250ms');
parseDuration('-1.5h');
parseDuration('0');

A string is numbers with a unit each (h, m, s, ms, us or µs, ns) after an optional sign, with a fraction in any of them and no spaces. Only 0 has no unit. A number is a float converted like the function of its unit: parseDuration('1.5h') is hours(1.5). So a fraction of a nanosecond is rounded, while Go drops it, and a number is as precise as a float, to 15 significant digits. A string that is not a duration or is out of range throws Time\TimeException.

Points in time

durationBetween() and shiftTime() count elapsed time between timestamps, so a change of the UTC offset (DST) does not count. shiftTime() drops the nanoseconds below a microsecond, which DateTimeImmutable cannot hold.

use function Thesis\Time\{durationBetween, shiftTime};

$expiresAt = shiftTime($clock->now(), $ttl);
$retainedSince = shiftTime($clock->now(), $retention->negate());
$elapsed = durationBetween($startedAt, $clock->now());

roundTimeTo() rounds a time to a multiple of a unit since 1970-01-01 00:00:00 UTC: rounded down, the times of one window give its start, a key for a limit or a metric.

use function Thesis\Time\{minutes, roundTimeTo};

$now = new DateTimeImmutable('2026-01-01 12:34:56 Europe/Moscow');

roundTimeTo($now, minutes(5), RoundingMode::NegativeInfinity); // 2026-01-01 12:30:00 Europe/Moscow

The multiples are of elapsed time, not of the wall clock: those of hours(24) are the midnights of UTC, whatever the time zone of the time, which is kept. The unit is positive and of whole microseconds, anything else throws \ValueError.

Time.Round() and Time.Truncate() of Go do the same from the year 1: the results match for a unit that divides a day, but a week starts on Thursday here and on Monday there.

The ends of int64 timestamps (the year ±292 billion) are out of reach: shiftTime() beyond them gives a wrong time or an error, as DateTimeImmutable::add() wraps around there, and roundTimeTo() within 512 seconds of them may give a time that is not a multiple of the unit.

PSR-20 clocks

WallClock and FrozenClock implement Psr\Clock\ClockInterface.

use Thesis\Time\{FrozenClock, WallClock};
use function Thesis\Time\sec;

$clock = new WallClock(); // the system time in the default time zone
$clock = new WallClock(new DateTimeZone('UTC'));

$clock = new FrozenClock(new DateTimeImmutable('2026-01-01 00:00:00 UTC')); // for tests
$clock->advance(sec(30));
$clock->now = new DateTimeImmutable('2027-01-01 00:00:00 UTC');

FrozenClock moves only when told: by advance() or by assigning $clock->now.

About

Time\Duration polyfill for PHP >=8.2, shorthands like sec(5) and toMs(), strings like 1h30m, PSR-20 clocks.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages