php DateTime with date without hours

set argument for constructor

$d = new \DateTime("midnight");

UPD: if an object already exists with any time

$d->settime(0,0);

result

DateTime Object
(
    [date] => 2016-04-20 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)

A very clean solution is to create a Value Object called Date that wraps a \DateTime and set the time part to zero. Here an example:

class Date
{
    private DateTimeImmutable $dateTime;

    public function __construct(DateTimeInterface $dateTime)
    {
        $this->dateTime = DateTimeImmutable::createFromInterface($dateTime)->setTime(0, 0);
    }

    public function format($format = ''): string
    {
        return $this->dateTime->format($format);
    }
}

You can also customize the format method to only use the 'Y-m-d' format.

Using a Value Object is much more expressive since reading the code you always know if your variable is just a date or a date with time.


For those of you who love doing stuff in the shortest possible way, here are one-liners for getting the current date or parsing a string date into a DateTime object and simultaneously set hours, minutes and seconds to 0.

For today's date:

$dateObj = new DateTime ("today");

For a specific date:

$dateObj = new DateTime ("2019-02-12"); //time part will be 0

For parsing a specific date format:

$dateObj = DateTime::createFromFormat ('!Y-m-d', '2019-02-12'); //notice the !

Tags:

Datetime

Php