Skip to content

Date and time

composer require quillstack/datetime

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/datetime

Usage

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);                   // now

Anything 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

ClassWhat it is
Datetimethe date and time; __toString() formats it
FormatInterfacethe format everything agrees on: HUMAN_DATE_TIME is Y-m-d H:i:s
DatetimeExceptionwhat everything here extends
Exceptions\InvalidDatetimeFormatOrKeyExceptionthe 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 stan

Docker

shell
docker-compose up -d
docker exec -w /var/www/html -it quillstack_datetime sh

License

MIT. See LICENSE.

Released under the MIT License.