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.
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
)
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 !
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With