首页 > 解决方案 > Getting closest DateTime using strtotime formats

问题描述

DateTime accepts formats acceptable to strtotime and as such DateTime::modify('previous sunday') and DateTime::modify('sunday next week') will alter the DateTime object's timestamp to be the previous Sunday and next Sunday, respectively.

How does one change the timestamp to the closest Sunday? For instance, if DateTime's timestamp was currently on a Monday, it would be changed to the previous Sunday, and if it was currently on a Friday, it would be changed to the next Sunday?

标签: phpdatetimestrtotime

解决方案


The relative time formats do not support a "closest day" (that I know of). You can compare the next and previous differences to see which is closest:

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

推荐阅读