Quick PHP tip: Initialize a DateTime object from string, but with time resetted
Section intitulée initialize-the-php-datetime-objectInitialize the PHP DateTime object
For a variety of reasons, we all have to initialize DateTime objects from strings like 2023-02-14
.
The quick and clean way to get an object from this kind of string is to use createFromFormat
method of DateTime
(or DateTimeImmutable
):
$dateTime = \DateTime::createFromFormat('Y-m-d', '2023-02-14');
var_dump($dateTime);
If I run this code today at 18:40:29, the output will be:
^ DateTime @1676367954 {#3
date: 2023-02-14 18:40:29.0 Europe/Paris (+01:00)
}
Yes, PHP sets the time of our new DateTime object with the current time, at the moment of the execution! 🧐
Section intitulée reset-the-timeReset the time
Now, let’s reset this weird time value. We can easily do it by calling the setTime
method on our DateTime object:
$dateTime = \DateTime::createFromFormat('Y-m-d', '2023-02-14');
$dateTime = $dateTime->setTime(0, 0);
var_dump($dateTime);
If I run this code today at 18:41:12, the output will be:
^ DateTime @1676329200 {#10
date: 2023-02-14 00:00:00.0 Europe/Paris (+01:00)
}
But we have to call two methods to get the desired value, isn’t there a more concise way to do this?
Yes there is! To reset the time at the object initialization, we can use a little-known and poorly documented feature of PHP, the BANG: !
.
$dateTime = \DateTime::createFromFormat('!Y-m-d', '2023-02-14');
var_dump($dateTime);
If I run this code today at 18:42:01, the output will be:
^ DateTime @1676329200 {#3
date: 2023-02-14 00:00:00.0 Europe/Paris (+01:00)
}
🎉 Tada! We have our DateTime object, with time at midnight, in one line of code!
Two alternative syntaxes exist, especially one without the discrete !
character
The first with |
at the end of the date string expression:
$dateTime = \DateTime::createFromFormat('Y-m-d|', '2023-02-14');
var_dump($dateTime);
If I run this code today at 18:42:01, the output will be:
^ DateTime @1676329200 {#3
date: 2023-02-14 00:00:00.0 Europe/Paris (+01:00)
}
Please note,
!
or|
character will reset not only time, but all values that are not present, or not parsed from your input string.
The second with midnight
word at the end of the date expression, which is more visible while you quickly read a piece of code:
$dateTime = new \DateTime('2023-02-14 midnight');
var_dump($dateTime);
If I run this code today at 18:42:01, the output will be:
^ DateTime @1676329200 {#3
date: 2023-02-14 00:00:00.0 Europe/Paris (+01:00)
}
Before leaving this page, did you know you can write this kind of code? 🤯
$firstDayOfNextMonth = new \DateTime('first day of next month');
$tomorrowAtNoon = new \DateTime('tomorrow noon');
$lastDayOfTheLastWeek = new \DateTime('last day of last week');
Let us know if you have any other quick tips about little-known features of PHP DateTime!
Commentaires et discussions
Ces clients ont profité de notre expertise
JoliCode accompagne l’équipe technique Dayuse dans l’optimisation des performances de sa plateforme. Nous sommes intervenus sur différents sujets : La fonctionnalité de recherche d’hôtels, en remplaçant MongoDB et Algolia par Redis et Elasticsearch. La mise en place d’un workflow de réservation, la migration d’un site en Twig vers une SPA à base de…
Nous avons développé une plateforme de site génériques autour de l’API Phraseanet. À l’aide de Silex de composants Symfony2, nous avons accompagné Alchemy dans la réalisation d’un site déclinable pour leurs clients. Le produit est intégralement configurable et supporte de nombreux systèmes d’authentification (Ldap, OAuth2, Doctrine ou anonyme).
Au fil de notre collaboration avec Deezer, nous avons été impliqués dans plusieurs initiatives visant à optimiser les performances de leur plateforme. Notre engagement initial s’est concentré sur le soutien et le conseil à l’équipe “Product Features” lors de leur projet de migration en cours. Nous avons apporté notre expertise pour résoudre…