Date and time
A date and time, written the way people read it.
PHP's own DateTime throws Exception for a string it cannot read, which is the one class a catch cannot be specific about. This wraps it: the same parsing, an exception of its own, and one format everything in the stack agrees on.
Requirements
- PHP 8.1 or newer
Installation
shell
composer require quillstack/datetimeUsage
php
use Quillstack\Datetime\Datetime;
(string) new Datetime(); // '2026-08-23 00:41:07'
(string) new Datetime('2026-01-15 08:30:00'); // '2026-01-15 08:30:00'
(string) new Datetime('2026-01-15'); // '2026-01-15 00:00:00'
(string) new Datetime('+1 day'); // tomorrow, at this time
(string) new Datetime(null); // nowAnything DateTime understands works, because it is what does the reading.
When the string is not a date
php
use Quillstack\Datetime\Exceptions\InvalidDatetimeFormatOrKeyException;
try {
new Datetime('the day before yesterday-ish');
} catch (InvalidDatetimeFormatOrKeyException $exception) {
// Invalid format: the day before yesterday-ish
}DateTime throws the base Exception for this, so catching it means catching everything. This one can be caught on its own, and it extends DatetimeException — as anything else this package ever throws will.
Technical documentation
| Class | What it is |
|---|---|
Datetime | the date and time; __toString() formats it |
FormatInterface | the format everything agrees on: HUMAN_DATE_TIME is Y-m-d H:i:s |
DatetimeException | what everything here extends |
Exceptions\InvalidDatetimeFormatOrKeyException | the string was not a date |
Datetime::NOW is 'now', which is also the default — so new Datetime() is this moment.
Unit tests
shell
composer test
composer test:coverage
composer stanDocker
shell
docker-compose up -d
docker exec -w /var/www/html -it quillstack_datetime shLicense
MIT. See LICENSE.