I have a DateTime of current day. I need to get two unix timestamps 开发者_如何学编程of beggining and ending of current week. How can I use dateperiod or dateinterval class?
$now = time();
$beginning_of_week = strtotime('last Monday', $now); // Gives you the time at the BEGINNING of the week
$end_of_week = strtotime('next Sunday', $now) + 86400; // Gives you the time at the END of the last day of the week
if (date('w', time()) == 1)
$beginning_of_week = strtotime('Today',time());
else
$beginning_of_week = strtotime('last Monday',time());
if (date('w', time()) == 7)
$end_of_week = strtotime('Today', time()) + 86400;
else
$end_of_week = strtotime('next Sunday', time()) + 86400;
public static function getDaysInWeek($timestamp)
{
$monday = idate('w', $timestamp) == 1 ? $timestamp : strtotime("last Monday", $timestamp);
$days = array();
for ($i = 0; $i < 7; ++$i)
{
$days[$i] = strtotime('+' . $i . ' days', $monday);
}
return $days;
}
The simplest way I can think of is this (I'm assuming the usual European week format, replace with other day names to your liking):
$when = new DateTimeImmutable('1974-08-21 22:30:00'); // Wednesday
echo $when->modify('monday this week')->format('r'), PHP_EOL;
echo $when->modify('monday next week -1 second')->format('r'), PHP_EOL;
Mon, 19 Aug 1974 00:00:00 +0200
Sun, 25 Aug 1974 23:59:59 +0200
I've used DateTimeImmutable
for simplicity, you can also use regular DateTime
and clone
objects.
Edge cases (date is either Monday or Sunday) should work as expected:
echo $when->modify('wednesday this week')->format('r'), PHP_EOL;
echo $when->modify('wednesday this week +1 day -1 second')->format('r'), PHP_EOL;
Wed, 21 Aug 1974 00:00:00 +0200
Wed, 21 Aug 1974 23:59:59 +0200
精彩评论