簡體   English   中英

使用日期時間獲取上周的最后一天

[英]Get last day of last week using 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獲取下個月第一周最后一天的最干凈方法是什么

使用格式占位符“ 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。

不要依賴format('l'),因為結果取決於環境。

我找到了解決方案,實際上很容易:

$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