thesis / time
Time\Duration polyfill for PHP >=8.2, shorthands like sec(5) and toMs(), PSR-20 clocks.
Fund package maintenance!
Requires
- php: ^8.2.2
- psr/clock: ^1.0
- symfony/polyfill-php84: ^1.34
Requires (Dev)
- testo/assert: ^0.1.17
- testo/codecov: ^0.2.5
- testo/data: ^0.1.10
- testo/test: ^0.1.8
- testo/testo: ^0.10.29
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Thesis Time
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\{format, ms, sec, toMs, toSecFloat}; $timeout = sec(1.5); toMs($timeout, RoundingMode::PositiveInfinity); // 1500 toSecFloat($timeout); // 1.5 format($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.
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". A deadline that has passed still gives 0 or less:
take max(1, ...) or check it with isPositive() 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, toSecFloat, toUsFloat}; $duration = sec(90.5); 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.
Checking, comparing, multiplying, formatting
use function Thesis\Time\{format, isNegative, isPositive, isZero, longest, multiply, shortest}; isZero($duration); isPositive($duration); isNegative($duration); shortest($a, $b, $c); longest($a, $b, $c); multiply($delay, 2); // exact multiply($delay, 1.5); // rounded to the nearest nanosecond multiply($delay, -1); format(duration(hours: 1, minutes: 2, sec: 3.5)); // 1h2m3.5s, like Duration.String() of Go
Points in time
between() and shift() count elapsed time between timestamps, so a change of the UTC offset (DST) does not count.
shift() drops the nanoseconds below a microsecond, which DateTimeImmutable cannot hold.
use function Thesis\Time\{between, shift}; $expiresAt = shift($clock->now(), $ttl); $retainedSince = shift($clock->now(), $retention->negate()); $elapsed = between($startedAt, $clock->now());
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.