DEV Community

Jimmy Klein
Jimmy Klein

Posted on

Create date easily in PHP

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"
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode
  • 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');
Enter fullscreen mode Exit fullscreen mode
  • First day of the year ?
// 2022-01-01 00:00:00.000000
$date = DateTime::createFromFormat('!Y', '2022');
Enter fullscreen mode Exit fullscreen mode
  • January 1, 1970 πŸ™ƒ?
// 1970-01-01 00:00:00.000000
$date = DateTime::createFromFormat('!', '');
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
ysf00009 profile image
YSF

:thanks

Collapse
 
fullfull567 profile image
fullfull567

Good reading, thank you so much

Collapse
 
klnjmm profile image
Jimmy Klein

Thank you for your feedback πŸ™

Collapse
 
ysf00009 profile image
YSF

:smile