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
Groupama Épargne Salariale digitalise son expérience client en leur permettant d’effectuer leurs versements d’épargne salariale en ligne. L’application offre aux entreprises une interface web claire et dynamique, composé d’un tunnel de versement complet : import des salariés via fichier Excel, rappel des contrats souscrits et des plans disponibles, …
L’équipe de Finarta a fait appel à JoliCode pour le développement de leur plateforme Web. Basée sur le framework Symfony 2, l’application est un réseau privé de galerie et se veut être une place de communication et de vente d’oeuvres d’art entre ses membres. Pour cela, de nombreuses règles de droits ont été mises en places et une administration poussée…
Dans le cadre d’une refonte complète de son architecture Web, le journal en ligne Mediapart a sollicité l’expertise de JoliCode afin d’accompagner ses équipes. Mediapart.fr est un des rares journaux 100% en ligne qui n’appartient qu’à ses lecteurs qui amène un fort traffic authentifiés et donc difficilement cachable. Pour effectuer cette migration, …