编程语言
首页 > 编程语言> > php – Zend_Date:如何获取即将到来的一天的日期?

php – Zend_Date:如何获取即将到来的一天的日期?

作者:互联网

我希望将来获得最接近的星期一的日期(即不是过去).

因此,如果今天是星期二(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)

我们可以通过在公式中添加modulus operator(百分号)来解决这个问题,以获得除法运算的剩余部分.

$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;
}

解决方法:

这是逻辑,布局:

$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.

标签:php,zend-framework,zend-date
来源: https://codeday.me/bug/20190607/1191950.html