withinboredom / time
Converting time to units
Installs: 1 640
Dependents: 1
Suggesters: 0
Security: 0
Stars: 13
Watchers: 3
Forks: 6
Open Issues: 0
Requires
- php: ^8.4
Requires (Dev)
- laravel/pint: ^1.16.2
- pestphp/pest: ^v3.8.2
Suggests
- crell/serde: ^1.3.2
README
Identity
This library uses some tricks to intern values so that two times are always equal to one another, no matter the distance in time or space.
use Withinboredom\Time; use Withinboredom\Time\Unit; $hour = Time::from(Unit::Hours, 1); $minutes = Time::from(Unit::Minutes, 60); echo $hour === $minutes ? 'true' : 'false' // outputs: true
Type Safety
You can ensure nobody will accidentally confuse seconds with milliseconds or minutes with seconds:
function sleep(Time $time): void { \sleep($time->as(Unit::Seconds)); } // Helper functions are included so you can type less code: sleep(Minutes(5));
Conversions and Math
You can easily convert between units and even perform operations, like sorting and arithmetic:
// use the hour constant to get one hour $hour = Hour; $hour = $hour->multiply(10)->add(Minutes(10)); // get 10:10 hours $interval = $hour->toDateInterval(); echo Hours(10) < $hour ? 'true' : 'false'; // output: true
Support for Crell\Serde
You cannot serialize/deserialize/clone Time
objects.
However, if you use something like Serde, you can still serialize your value objects:
class CacheItem { public function __construct( #[Field('expiration_in_seconds')] #[TimeAs(Unit::Seconds)] public Time $expiration, ) {} } $serde = new SerdeCommon(handlers: new \Withinboredom\Time\SerdeExporter()); $serde->serialize(new CacheItem(Minutes(5)), 'json');
The above will be serialized (and deserialized) from:
{ "expiration_in_seconds": 300 }
Units
- Nanoseconds
- Microseconds
- Milliseconds
- Minutes
- Hours
- Days
- Weeks
FAQ
Why not months/years?
There are no set days in a month/year, so it’s better to use DateInterval
for those types of measures.
Why does this exist?
I don’t like magic numbers.
How performant is this?
The main overhead is in autoloading and function-call overhead. Thus, if realtime performance is a concern, you might want to stick to magic numbers.
Developing
If you wish to create a PR or update the code here:
- Clone the repo
composer install
to install test dependenciesyarn
to install git hooks for formatting- Open in favorite IDE.
Code Standards
Per coding styles are followed.