4

我想获得未来最近的星期一的日期(即不是过去)。

因此,如果今天是星期二(2009 年 12 月 1 日),我想得到星期一(2009 年 12 月 7 日)的日期。

我该怎么做Zend_Date

解决方案:

假设今天是星期二,我们想得到即将到来的星期一。星期一是未来 6 天。因此,我们将添加 6 天来获得星期一的日期。

//like so:
$tuesday = Zend_Date::now();
$nextMonday = $tuesday->addDay(6);

要动态地执行此操作,我们需要确定今天是一周中的哪一天:

$today = Zend_Date::now();
$dayNumber = $today->get(Zend_Date::WEEKDAY_DIGIT);
//dayNumber will now be equal to the numeric day of the week (0-6)
//example:
$weekdays = array(
    0 => 'sunday',
    1 => 'monday',
    2 => 'tuesday' //etc...
);

要确定我们需要添加多少天才能获得所需的未来日期,我们执行以下操作:

$daysToAdd = ( $dayWanted - $todayDayNumber + 7 );
#      $dayWanted = monday(1)
# $todayDayNumber = tuesday(2)
#               7 = number of days in a week (we don't want a negative number)
#       1 - 2 + 7 = 6 days into the future
$nextMonday = $today->addDay($daysToAdd);

假设我们想要的那一天是星期三(明天),未来的某一天。我们之前的解决方案不起作用:

$daysToAdd = ( $dayWanted - $todayDayNumber + 7 );
#      $dayWanted = wednesday(3)
# $todayDayNumber = tuesday(2)
#               7 = number of days in a week
#       3 - 2 + 7 = 8 days into the future (not 1)

我们可以通过将模运算符(百分号)添加到我们的公式中来解决这个问题,以获得除法运算的余数。

$daysToAdd = ( $dayWanted - $todayDayNumber + 7 ) % 7;
# (3 - 2 + 7) % 7
# $daysToAdd == 1 (remainder of 8 divided by 7)
$tomorrow = $today->addDay($daysToAdd);

现在我们的公式将按预期工作......除了一件事。如果今天是星期二,我想得到下一个星期二,我们的公式将在今天返回,而不是从今天开始一周:

$daysToAdd = ( $dayWanted - $todayDayNumber + 7 ) % 7;
# (2 - 2 + 7) % 7 == 0
# 7 goes into 7 evenly with no remainder

我们将不得不添加一个检查以确保它不等于零。

if ($daysToAdd == 0) {
    //give me the date a week from today, not today's date
    $daysToAdd = 7;
}

最终解决方案:

public function outputDate()
{
    $monday = $this->getDateOfNext('monday');
    echo 'today: ' . Zend_Date::now()->toString(Zend_Date::RFC_850) . "<br>";
    echo "monday: " . $monday->toString(Zend_Date::RFC_850);
}

private function getDateOfNext($dayWanted)
{
    $weekdays = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
    if (!in_array($dayWanted, $weekdays)) {
        throw new Exception("'$dayWanted' not found in array of possible weekdays");
    }
    $weekdays = array_flip($weekdays);
    $date = Zend_Date::now();
    $today = $date->get(Zend_Date::WEEKDAY_DIGIT);
    $daysToAdd = ( $weekdays[$dayWanted] - $today + 7 ) % 7;
    if ($daysToAdd == 0) {
        //give me the date a week from today, not today's date
        $daysToAdd = 7;
    }
    $date->addDay($daysToAdd);
    return $date;
}
4

1 回答 1

6

逻辑如下:

$days_per_week = 7;
$weekdays = array_flip(array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'));

$day_wanted = 'mon';
$days_forward =
  ( $weekdays[$day_wanted] - $date->get(Zend_Date::WEEKDAY_DIGIT) + $days_per_week )
  % $days_per_week;

$date->addDay($days_forward);

这对任何 $day_wanted.

于 2009-12-19T02:23:35.077 回答