带strtotime的日期函数将指向上一个星期天,但我希望它是最近的星期天


date function with strtotime is going to last sunday, but i want it to be most recent sunday

我有以下代码行

$sunday = date ("m/d", strtotime("last sunday"));
$saturday = date("m/d",strtotime("this saturday"));

,但如果今天是星期天,它将不选择今天。这周剩下的几天都没问题,因为上个星期天就是今天。我想这样做:

if (today is not sunday) {set to last sunday }else{ set to today }

同样适用于星期六。

编辑:

这样做是否可以接受,或者是否有更好的方法:

$today = date('D', strtotime("today"));
if( $today === 'Sun') {
    $sunday = date ("m/d", strtotime("today"));
}else{
    $sunday = date ("m/d", strtotime("last sunday"));
}
if ( $today === "Sat"){
    $saturday =  date ("m/d", strtotime("today"));
}else{
    $saturday = date("m/d",strtotime("this saturday"));
}

我相信你自己也能想到这个,但是…

:

function today_or_lastday ($day) {
    return date('m/d', strtotime("7 days ago")) == date('m/d', strtotime("last $day"))
        ? date('m/d', strtotime("today"))
        : date('m/d', strtotime("last $day"));
}

:

$sunday = today_or_lastday("sunday");
$saturday = today_or_lastday("saturday");

我将使用这样的行来获取最近/当前的周六和周日:

$sunday   = date( 'm/d', time() - ( date( 'w' ) * 3600*24 ) );
$saturday = date( 'm/d', time() - ( ( date( 'w' ) + 1 ) % 7 * 3600*24 ) );

对于星期天,我们从星期天算起现在-天。

date('w')给出了工作日(0=Sunday, 1=Monday,…)6=星期六),然后减去自星期日以来已经过去的天数(以秒3600*24计算)。

对于星期六,我们做同样的事情,但添加了一点数学技巧来调整它是第6天。

相关文章: