New in Symfony 6.4: DatePoint
October 30, 2023 • Published by Javier Eguiluz
Symfony 6.4 is backed by:
In Symfony 6.2 we introduced the Clock component to improve the testability
of your time-sensitive code. In Symfony 6.4 we're introducing DatePoint
, a
new PHP date/time class that integrates seamlessly with the Clock component.
The main advantage of DatePoint
over PHP's DateTime
and DateTimeImmutable
it that is uses the global static clock of the Clock
component to set the
current time. This means that if you did any changes to the clock, it will be
reflected when creating new DatePoint
instances:
1 2 3 4
use Symfony\Component\Clock\DatePoint;
// gets the current time from the date/time defined by Clock
$createdAt = new DatePoint();
The DatePoint
class extends DateTimeImmutable
, so you can use it in your
code anywhere a DateTimeImmutable
or DateTimeInterface
is expected.
DatePoint
also includes some utilities to handle date/time values, although
is not meant to replace third-party libraries that provide lots of utilities to
work with date/time values:
1 2 3 4 5 6 7 8
// set the current time explicitly
$firstPublicCommitOfSymfony = 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 full integration with the Clock
component, some utilities and better
error handling.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
> This means that if you did any changes to the clock, it will be reflected when creating new `DatePoint` instances
I am wondering if the examples could provide simple example how datetime is overridden with Clock and how it affects `new DatePoint()` instance (comparing to regular `new DateTime[Immutable]()`). Current examples are OK, but I believe less experienced people may find it not obvious.