正如标题所说,我想获取 PHP 上周的星期六日期和本周的星期六日期,并限制从星期六而不是星期一开始一周。
我首先使用
strtotime('saturday last week')
和 strtotime('saturday this week')
或 new DateTime("saturday last week")
和 new DateTime("saturday this week")
但显然没有给出预期的结果,因为一周从星期一开始。
例如,如果今天是 2024-03-04,则结果应该是:
最简单的方法是什么?
如果我正确的话,您可以使用
DateTime
类和 modify
函数来查找所需的周六日期。所以逻辑上应该是:
// Get last week's Saturday date.
$lastSaturday = new DateTime('last saturday');
$lastSaturday->modify('-1 week'); // Adjust for week starting on Saturday.
echo 'Last Saturday: ' . $lastSaturday->format('Y-m-d') . PHP_EOL;
// Get this week's Saturday date.
$thisSaturday = new DateTime('saturday this week');
echo 'This Saturday: ' . $thisSaturday->format('Y-m-d') . PHP_EOL;
通过调整上周六的日期减去一周,您可以将其与从周六开始的一周对齐。
我不确定我是否正确理解你的问题。在你的例子中你说
如果今天是 2024-03-04,结果应该是:
上周六:2024-02-24
本周六:2024-03-02
但听起来你只想争取最后一个星期六。
要获得上周六,您可以使用此代码:(在此处测试)
function lastWeekSaturday(int $timestamp){
$enteredDayOfWeek = date("l",$timestamp);
if( $enteredDayOfWeek == 'Saturday' ){
$lastWeekSaturday = strtotime('1 saturday ago', $timestamp);
}else{
$lastWeekSaturday = strtotime('2 saturday ago', $timestamp);
}
return date('Y-m-d',$lastWeekSaturday);
}
echo lastWeekSaturday(time()) ; // prints the last saturday date