More readable way to get end of given day nowdays would be
function endOfDay(string $dateToChange): \DateTime
{
return (new \DateTime($dateToChange))->setTime(23, 59, 59);
}
var_dump(endOfDay('2019-05-04'));
will give you (take note that \DateTime
contains TZ info)
object(DateTime)#1 (3) {
["date"]=> string(26) "2019-05-04 23:59:59.000000"
["timezone_type"]=> int(3)
["timezone"]=> string(3) "UTC"
}
But, as @Wiimm mentioned in his answer, this way you'll be missing a second out of day. So it would be more correct to use
function startOfDay(\DateTime $dt): \DateTime
{
return (clone $dt)->setTime(0, 0, 0);
}
and correct comparison:
$date = new \DateTime('2019-05-04 15:25:13'); // 2019-05-04 15:25:13.000000
$dateNextDay = (clone $date)->modify('+1 day'); // 2019-05-05 15:25:13.000000
$isInBetween = startOfDay($date) <= $date && $date < startOfDay($dateNextDay); // true
Take note of using clone
(otherwise original $date
would be modified) and completely switching to DateTime
.
Most of ORMs already knows how to work with \DateTime
, but if you need to convert it to string:
echo $date->format('Y-m-d H:i:s'); // 2019-05-04 00:00:00