New in Symfony 6.4: DatePoint
Contributed by
Nicolas Grekas
in #51415.
Working with dates in PHP can sometimes get a bit quirky. For example, if you modify
a DateTime variable to generate a new date, the original variable also changes.
That’s why PHP had to introduce the DateTimeImmutable to solve this issue.
Sadly this class also has some quirks, such as returning false instead of
throwing exceptions when an error happens.
That’s why in Symfony 6.4 we’re introducing DatePoint, a new class to work
with dates in PHP. First, this class extends DateTimeImmutable, so you can
use it anywhere a DateTimeImmutable or DateTimeInterface is expected.
Second, this class seamlessly integrates with the Clock component that
we introduced in Symfony 6.2. This means that if you did any changes to the
clock, it will be reflected when creating new DatePoint instances:
use SymfonyComponentClockDatePoint;
// gets the current time from the date/time defined by Clock
$createdAt = new DatePoint();
// set the current time explicitly
$firstPubliCommitOfSymfony = new DatePoint(‚2005-10-18 16:27:36 Europe/Paris‘);
// use current Clock time but specify a timezone
$orderCreatedAt = new DatePoint(timezone: new DateTimezone(‚UTC‘));
// use an existing date as the reference to create a DatePoint
$welcomeDiscountValidUntil = new DatePoint(‚+1 month‘, reference: $user->getSignedUpAt());
Another improvement of the DatePoint class is that errors (such as creating
invalid dates or trying to do invalid date modifications) no longer return false
but throw a DateMalformedStringException. This exception was introduced in PHP 8.3
but thanks to Symfony PHP 8.3 polyfill you can use it starting from PHP 7.1.
In summary, DatePoint is a drop-in replacement of PHP date/time classes that
provides many utilities, full integration with the Clock component and better
error handling.
Symfony Blog