A read-only split of
packages/timefrom the thesis-php/thesis monorepo: issues and pull requests go there.
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');composer require thesis/timeRequires PHP 8.2.2+, 64-bit or 32-bit. No extensions. Below PHP 8.4 \RoundingMode comes from symfony/polyfill-php84.
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; // falseThe 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).
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 partsA value out of range throws Time\TimeException, NAN and INF throw \ValueError.
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); // 1toNs() 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.
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.025138888888888888For 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.
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_TIMEOUTandCURLOPT_CONNECTTIMEOUTtake 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), passmax(0.001, toSecFloat($timeout)).timeoutof Symfony limits the wait between two chunks, the whole request is limited bymax_duration. - PDO. The time to connect in MySQL and Postgres, where
0waits as long as the system does. In SQLite the wait for a locked database, where0fails at once. stream_set_timeout(). The microseconds, with0seconds before them: PHP carries whole seconds over,stream_set_timeout($stream, 0, toUs($timeout, RoundingMode::PositiveInfinity)). No limit is-1second.- PSR-16. A negative TTL deletes the item too,
nullis the default TTL of the cache. - Postgres. A number without a unit is milliseconds, also in
lock_timeoutandidle_in_transaction_session_timeout.
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.
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.
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.
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/MoscowThe 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.
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.