使用datetime获取上周的最后一天

时间:2017-03-21 18:42:09

标签: php datetime

我已尝试使用以下代码来获取下个月的最后一天:

$paymentMonth = "2017-07";
$wee = new \DateTime($paymentMonth);
$firstDate = clone $wee->modify(('Sunday' == $wee->format('l')) ? 'Monday last week' : 'Monday this week'); //Monday of last week of previous month

$lastDate = clone $wee->modify('+1 month')->modify(('Sunday' == $wee->format('l')) ? 'Sunday last week' : 'Sunday this week');
/**^^^^
  * This works in most cases of months
  * but for july 2017, I want the last day of the first week of next month.
  */

echo $firstDate->format('Y-m-d'); //Gives 26-june
echo $lastDate->format('Y-m-d'); //Gives 30-july in this case i want the 31 of july...

使用DateTime

获取下个月第一周最后一天的最简洁方法是什么?

2 个答案:

答案 0 :(得分:1)

使用格式占位符'w'获取该月的第一天的星期几。然后减去你想要获得的日期的相对数量(星期日= 7,星期六= 6,星期五= 5,依此类推)。如果您想获得该月的第一个星期日:

$paymentMonth = '2017-06-01';
$d = new DateTime($paymentMonth);
$w = $d->modify('+1 month')->format('w'); // * Returns 6 as 1st July 2017 is Saturday
$sun = (7-$w + 1)%7; // * First Sunday is 7-$w + 1 = 2
$lastDate = new DateTime($d->format('Y-m') . "-$sun");

模块%7是必需的,因为星期日格式('w')返回0。

不要依赖格式('l'),因为结果与环境有关。

答案 1 :(得分:0)

我找到了解决方案,非常容易实现:

$paymentMonth = '2017-07';
$fweek = new \DateTime($paymentMonth);
$firstDate = $fweek->modify(('Sunday' == $fweek->format('l')) ? 'Monday last week' : 'Monday this week'); //Monday of last week of previous month
$lweek = new \DateTime($paymentMonth);
$lastDate = $lweek->modify('+1 month')->modify(('Sunday' == $lweek->format('l')) ? 'Sunday last week' : 'Sunday this week'); //Sunday of first week of next month

echo $firstDate->format('Y-m-d') . ' - ' . $lastDate->format('Y-m-d');