Sergey Onishchenko Sergey Onishchenko - 7 months ago 26
PHP Question

php DateTime with date without hours

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.

Answer

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
)
Comments