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
Axiatel à fait appel à JoliCode afin d’évaluer les développements effectués par la société. A l’issue d’un audit court, nous avons présenté un bilan de la situation actuelle, une architecture applicative cible, et nos recommandations en vue d’une migration en douceur vers le modèle applicatif présenté.
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…
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…