Modern PHP, soft skills, productivity and time management.

\DateTime class is cool.

Yeah, it is.

Do you want yesterday at 6 am? `new \DateTime(“yesterday 06:00:00”);`
Do you want two weeks ago at noon? `new \DateTime(“-2 weeks 12:00:00”);`
Do you want just 2 minutes ahead? `new \DateTime(“+2 minutes”);`

`\DateTime` class parses string given in the constructor and translates it into valid date and time. It is awesome when you have to compute intervals for SQL query.

$from = new \DateTime("now 00:00:00");
$to = new \DateTime("now 23:59:59");

$sql = sprintf(
    "SELECT * FROM table WHERE `date` BETWEEN '%s' AND '%s'",
    $from->format("Y-m-d H:i:s"),
    $to->format("Y-m-d H:i:s")


`format` method is also cool.

Do you want to get only year, month and day from DateTime object? `$date = (new \DateTime(“now”))->format(“Y-m-d”);`
Do you want only date and hour? `$date = (new \DateTime(“now”))->format(“Y-m-d H:00:00”);`

Do you want to get data from database from current hour yesterday (e.g. for statistics)?

$yesterday = new \DateTime("yesterday");

$sql = sprintf(
    "SELECT * FROM table WHERE created_at BETWEEN '%s' AND '%s'",
    $yesterday->format("Y-m-d H:00:00"),
    $yesterday->format("Y-m-d H:59:59")

It’s pretty damn easy. Just learn what are available formats.

Once again: `\DateTime` class is cool.


  1. ignace butera

    DateTimeImmutable is cooler

    • krzych

      Ok, let’s say `DateTimeInterface` is cool 😉

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2024 Krzych Jończyk

Theme by Anders NorenUp ↑