简体   繁体   English

使用日期时间获取上周的最后一天

[英]Get last day of last week using datetime

I have tried the following code to get the last day of week in the next month: 我已经尝试使用以下代码来获取下个月的最后一天:

$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...

What is the cleanest way to get the last day of first week of next month using DateTime 使用DateTime获取下个月第一周最后一天的最干净方法是什么

Use format placeholder 'w' to obtain day of week of first of the month. 使用格式占位符“ w”来获取每月第一天的星期几。 Then subtract the relative number of the day you want to obtain (Sunday = 7, Saturday = 6, Friday = 5 and so on). 然后减去您要获取的相对天数(星期日= 7,星期六= 6,星期五= 5,依此类推)。 If you want to obtain first Sunday of the month: 如果要获取每月的第一个星期日:

$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");

Module %7 is required as on Sunday format('w') returns 0. 需要模块%7,因为星期日格式('w')返回0。

Don't rely on format('l') as result is environment dependent. 不要依赖format('l'),因为结果取决于环境。

I found the solution, was pretty easy actualy : 我找到了解决方案,实际上很容易:

$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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM