p-sam / duration-immutable
Immutable class to store time durations
Installs: 6 874
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: >=7.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- korbeil/phpstan-generic-rules: ^0.2.2
- phpstan/phpstan: ^0.11.19
- phpstan/phpstan-deprecation-rules: ^0.11.2
- phpstan/phpstan-strict-rules: ^0.11.1
This package is auto-updated.
Last update: 2024-12-01 12:36:55 UTC
README
Immutable PHP class to store time durations while not being tied to a Date.
Internally uses DateInterval and DateTime to do the actual operations.
Installation
Install with composer:
$ composer require p-sam/duration-immutable
Usage
Instanciating
use SP\DurationImmutable\DurationImmutable; DurationImmutable::fromSeconds(2); // 2s DurationImmutable::fromSeconds(-30); // - 30s DurationImmutable::fromSeconds(92, 0.200130); // 1m 32s 200ms 130µs DurationImmutable::fromPHPDateInterval(new DateInterval('P1DT4H')); // 1d 4H $refDate = DateTimeImmutable::createFromFormat(DateTimeImmutable::ATOM, '2020-01-10T00:00:00+00:00'); DurationImmutable::fromPHPDateInterval( new DateInterval('P1M3D'), $refDate ); // 34d // refer to DateInterval::createFromDateString // for documentation on accepted formats DurationImmutable::fromHuman('1 hour - 15 minutes'); // 45m DurationImmutable::fromHuman('yesterday'); // - 1d
Ops
use SP\DurationImmutable\DurationImmutable; $duration = DurationImmutable::fromHuman('120 minutes'); // 2h $duration->abs(); // 2h $duration->add(DurationImmutable::fromHuman('30 minutes')); // 2h 30m $duration->sub(DurationImmutable::fromHuman('3 hours + 10 minutes')); // - 1h 10m $duration->mul(2.5); // 5h $duration->div(-4); // - 30m $dateTime = new DateTimeImmutable(); $duration->addTo($dateTime); // now + 2h $duration->toSeconds(); // 7200 $duration->toIntervalSpec(); // "PT2H" $duration->toPHPDateInterval(); // DateInterval("PT2H")