Just datetime
$beginOfDay = DateTime::createFromFormat('Ymd H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Ymd 00:00:00'))->getTimestamp(); $endOfDay = DateTime::createFromFormat('Ymd H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Ymd 23:59:59'))->getTimestamp();
First, a DateTime object is created, and the timestamp is set to the desired timestamp. Then the object is formatted as a string that sets the hour / minute / second at the beginning or end of the day. Finally, a new DateTime is created from this line and the timestamp is retrieved.
Read
$dateTimeObject = new DateTime(); $dateTimeObject->setTimestamp($timestamp); $beginOfDayString = $dateTimeObject->format('Ymd 00:00:00'); $beginOfDayObject = DateTime::createFromFormat('Ymd H:i:s', $beginOfDayString); $beginOfDay = $beginOfDayObject->getTimestamp();
We can get the end of the day in an alternative way using this longer version:
$endOfDayObject = clone $beginOfDayOject(); // Cloning because add() and sub() modify the object $endOfDayObject->add(new DateInterval('P1D'))->sub(new DateInterval('PT1S')); $endOfDay = $endOfDayOject->getTimestamp();
Timezone
You can also set the time zone by adding a time indicator to a format such as O and specifying a timestamp after creating the DateTime object:
$beginOfDay = DateTime::createFromFormat('Ymd H:i:s O', (new DateTime())->setTimezone(new DateTimeZone('America/Los_Angeles'))->setTimestamp($timestamp)->format('Ymd 00:00:00 O'))->getTimestamp();
Flexibility DateTime
We can also get other information, such as the beginning / end of the month or the beginning / end of the hour by changing the specified second format. Monthly: 'Ym-01 00:00:00' and 'Ymt 23:59:59' . Per hour: 'Ymd H:00:00' and 'Ymd H:59:59'
Using various formats in combination with add () / sub () and DateInterval objects, we can get the beginning or end of any period, although you will need to take care to cope with leap years correctly.
Relevant Links
From the PHP docs:
Robert Hickman Jan 04 '16 at 18:07 2016-01-04 18:07
source share