Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php DateTime with date without hours

Tags:

php

datetime

new \DateTime();
/*
DateTime Object
(
    [date] => 2016-04-20 04:45:24.000000
    [timezone_type] => 3
    [timezone] => UTC
)
*/  

How do I trim hours to get my DateTime object like this:

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

The only way that I know is:

$date = new \DateTime();
$date->format('Y-m-d');
$date = new \DateTime($date->format('Y-m-d'));

But I don't like this solution.

like image 591
Sergey Onishchenko Avatar asked Apr 20 '16 11:04

Sergey Onishchenko


3 Answers

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
)
like image 83
splash58 Avatar answered Oct 23 '22 15:10

splash58


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 !
like image 8
Cláudio Silva Avatar answered Oct 23 '22 16:10

Cláudio Silva


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.

like image 1
Luigi C. Avatar answered Oct 23 '22 16:10

Luigi C.