代码之家  ›  专栏  ›  技术社区  ›  Enthu

如何在没有星期日的情况下将日期和日期保存到单独的数组中?

php
  •  0
  • Enthu  · 技术社区  · 7 年前

    $date = new DateTime("+ 1 day", new DateTimeZone('Asia/Thailand') );
    
    for ($i=1; $i<=5; $i++) {
        $date->modify("+1 weekday");
        $delivery_dates[] = $date->format("m/d/Y");
        $delivery_days[] = $date->format("l, d F Y");
    }
    

    目前,我得到以下信息-

    我使用了以下方法-

    for ($i=1; $i<=5; $i++) {
        $date->modify("+1 weekday");
        if ($date->format("N") !== 7 {
           $delivery_dates[] = $date->format("m/d/Y");
           $delivery_days[] = $date->format("l, d F Y");
        }
    }
    

    上面的代码仍然显示在星期天。

    2 回复  |  直到 7 年前
        1
  •  0
  •   TsV    7 年前
        $from = '2018-10-10';
        $to = '2018-12-10';
        $start = new \DateTime($from);
        $end   = new \DateTime($to);
        $interval = \DateInterval::createFromDateString('1 day'); // 1 day === P1D, 5 month and 5 years === P5M5Y
        $period   = new \DatePeriod($start, $interval, $end); // A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.
        // new \DatePeriod(10-10-2010, 5, 30-10-2010) ===> [10-10-2010, 15-10-2010, 20-10-2010, 25-10-2010, 30-10-2010]
    
        $result = [];
    
        foreach ($period as $day) {
            if (! in_array($day->format('w'), [0, 6])) { // check every date in period, ->format('w'): w - number of day; Monday = 1 or 7 (depends on wat day declared first)
                $result['date'][] = $day->format("m/d/Y");
                $result['day'][] = $day->format("l, d F Y");
            }
        }
    
        2
  •  0
  •   k0pernikus    7 年前

    假设您可以使用 Carbon ,一种实现方法是在while循环的帮助下生成范围,如果不是星期天,则只添加一个日期,同时确保获得所需的天数(在您的情况下为5天)。

    /**
     * @param int $amount
     * @return Carbon[]
     */
    public function getDeliveryDates($amount = 5): array
    {
        $days = [];
        $current = Carbon::today();
    
        while (\count($days) < $amount) {
            $day = clone $current; // addDay works on instance, cloning it
            $day->addDay();
            $current = $day; // setting current to current day, so that it will iterate
            if ($current->isSunday()) {
                continue;
            }
    
            $days[] = $current;
        }
    
        return $days;
    }
    

    $formattedDates = [];
    $formattedDays = [];
    foreach (getDeliveryDates() as $date) {
        $formattedDates[] = $date->format('m/d/Y');
        $formattedDays[] = $date->format('l, d F Y');
    }
    
    推荐文章