The simplest way to create dates in PHP is to instantiate an object of the DateTime
class.
$date = new DateTime();
// "2022-12-19 08:33:03.003983"
We can also pass a string
as a parameter to this constructor:
// Current date and time ("2022-12-19 08:33:03.003983")
// Default value of the constructor
$date = new DateTime("now");
// This morning at midnight ("2022-12-19 00:00:00.000000")
$date = new DateTime("midnight");
// Tomorrow at midnight ("2022-12-20 00:00:00.000000")
$date = new DateTime("tomorrow");
// Last day of december at midnight ("2022-12-31 00:00:00.000000")
$date = new DateTime("last day of december");
From a format
We can also create dates from a format that we define.
// 2022-12-21 08:33:03.003983
$date = DateTime::createFromFormat('Y-m-d', '2022-12-21');
We see here that the hours, minutes and seconds are initialized with the values of the current time. If we want to reset these values to 0
, we can use !
.
- A date at midnight?
// 2022-12-19 00:00:00.000000
$date = DateTime::createFromFormat('!Y-m-d', '2022-12-19');
- But it also works with days, months and years. The first day of the month?
// 2022-12-01 00:00:00.000000
$date = DateTime::createFromFormat('!Y-m', '2022-12');
- First day of the year ?
// 2022-01-01 00:00:00.000000
$date = DateTime::createFromFormat('!Y', '2022');
- January 1, 1970 π?
// 1970-01-01 00:00:00.000000
$date = DateTime::createFromFormat('!', '');
Thank you for reading, and let's stay in touch !
If you like this article, please share. You can also find me on Twitter/X for more PHP tips.
Top comments (4)
:thanks
Good reading, thank you so much
Thank you for your feedback π
:smile