使用 strtotime 格式获取最接近的 DateTime

Getting closest DateTime using strtotime formats

DateTime 接受 strtotime 可接受的格式,因此 DateTime::modify('previous sunday')DateTime::modify('sunday next week') 将分别将 DateTime 对象的时间戳更改为上一个星期日和下一个星期日。

如何将时间戳更改为最近的星期日?比如DateTime的时间戳当前是周一,就改成上周日,如果现在是周五,就改成下周日?

相对时间格式不支持 "closest day"(据我所知)。您可以比较下一个和上一个差异,看看哪个最接近:

function closestWeekday(DateTimeInterface $date, int $dayOfWeek) {
    if( !($date instanceof DateTimeImmutable) ) {
        $date = DateTimeImmutable::createFromMutable( $date );
    }
    $dowStr = jddayofweek($dayOfWeek, CAL_DOW_LONG);
    $prevDate = $date->modify('previous ' . $dowStr);
    $nextDate = $date->modify('this ' . $dowStr);
    $prevDiff = $prevDate->diff($date);
    $nextDiff = $nextDate->diff($date);
    return ($prevDiff->days < $nextDiff->days) ? $prevDate : $nextDate;
}


$wed = new DateTime('wednesday');
$thur = new DateTime('thursday');

// Find closest Sunday to this Wednesday
$closestDay1 = closestWeekday($wed, 6);

// Find closest Sunday to this Thursday
$closestDay2 = closestWeekday($thur, 6);

// Second argument is an integer representing the day of week you want to find
// 0 = Monday, 1 = Tuesday, 2 = Wednesday, ..., 6 = Sunday