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
Nous avons entrepris une refonte complète du site, initialement développé sur Drupal, dans le but de le consolider et de jeter les bases d’un avenir solide en adoptant Symfony. La plateforme est hautement sophistiquée et propose une pléthore de fonctionnalités, telles que la gestion des abonnements avec Stripe et Paypal, une API pour l’application…
À l’occasion de la 12e édition du concours Europan Europe, JoliCode a conçu la plateforme technique du concours. Ce site permet la présentation des différents sites pour lesquels il y a un appel à projets, et encadre le processus de recueil des projets soumis par des milliers d’architectes candidats. L’application gère également toute la partie post-concours…
Afin de poursuivre son déploiement sur le Web, Arte a souhaité être accompagné dans le développement de son API REST “OPA” (API destinée à exposer les programmes et le catalogue vidéo de la chaine). En collaboration avec l’équipe technique Arte, JoliCode a mené un travail spécifique à l’amélioration des performances et de la fiabilité de l’API. Ces…