DEV Community

Jimmy Klein
Jimmy Klein

Posted on

4

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay