如何获得给定月份的周数以及星期一开始的星期和星期五结束。以及所有周开始日期和结束日期

时间:2013-06-29 06:57:17

标签: php date smarty

我希望获得所有周的给定月份,并且我希望获得周开始日期和周结束日期,并且周持续时间是星期一至星期五。

1 个答案:

答案 0 :(得分:0)

以下是用于生成日历的非常简单的PHP脚本的一部分。您应该能够使用/修改它来回答您的所有问题:

class Calendar {
    public $calendar;
    public $current_date;
    public $current_month_days;
    public $current_date_str;
    public function __construct($month = FALSE, $expand = FALSE)
    {
        try {
            $date_obj = new DateTime($month);
            $this->current_date_str = $date_obj->getTimestamp();
        } catch ( Exception $e ) {
            $this->current_date_str = time();   
        }
        $this->current_date = date('Y-m', $this->current_date_str);
        $this->get_current_month_days();
        $this->build_calendar();
    }
    public function get_current_month_days()
    {
        $days_in_month = cal_days_in_month(CAL_GREGORIAN, date('m', strtotime($this->current_date)), date('Y', strtotime($this->current_date)));
        for ( $i = 1; $i <= $days_in_month; $i++ ) {
            $this->current_month_days[$this->current_date.'-'.sprintf('%02d', $i)] = '';
        }
        return $this->current_month_days;
    }
    public function build_calendar()
    {
        $this->calendar = array('row1' => array());
        $day_start = date('w', strtotime(key(array_slice($this->current_month_days, 0, 1))));
        if ( $day_start > 0 ) {
            $this->calendar['row1'] = array_pad($this->calendar['row1'], $day_start, FALSE);    
        }
        $i = $day_start;
        $row = 1;
        foreach ( $this->current_month_days as $k => $v ) {
            if ( $i == 7 ) {
                $i = 0;
                $row++; 
            }
            $this->calendar['row'.$row][$k] = $k;
            $i++;
        }
        if ( sizeof($this->calendar['row'.$row]) != 7 ) {
            $this->calendar['row'.$row] = array_pad($this->calendar['row'.$row], 7, FALSE);
        }
    }
}