PHP如何判断每个月的每一周是几号到几号?

叶问
  • 77

业务需要,根据当前时间判断这个月每一周是几号到几号,比如这个月,第一周是1号到5号,第二周是6号到12号。。返回数组最好,不要年的,要月,俺是菜鸟,希望大神给予代码个思路...谢谢了

回复
阅读 2.9k
5 个回答
✓ 已被采纳

偶来凑个热闹,来个面向对象版本的:


/**
 * @param DateTime|int|string|null $date 可以是DateTime对象、时间戳、字符串形式的日期或者空值表示当前月份
 * @return array [[1,2,3,4,5], ...] 分别表示这月每一周都是几号到几号
 */
function getWeeksOfMonth($date=null){
    if (is_numeric($date)){
        $d = new DateTime();
        $d->setTimestamp($date);
        $date = $d;
    } else if (is_string($date)){
        $date = new DateTime($date);
    } else if ($date instanceof DateTime){
        // nothing to do
    } else if (!$date){
        $date = new DateTime();
    } else {
        throw new InvalidArgumentException("Invalid type of date!");
    }


    // 当前日期是在一个月里面是第几天
    //  j: 月份中的第几天,没有前导零    1 到 31
    $dateDay = (int)$date->format('j');

    // 这个月1号是星期几
    // N: 1(表示星期一)到 7(表示星期天)
    $beginWeekDay = (int)$date->sub(new DateInterval("P" . ($dateDay - 1) . "D"))->format('N');

    // 这个月最后一天是几号
    // j    月份中的第几天,没有前导零    1 到 31
    $endMonthDay = (int)($date->add(new DateInterval('P1M'))->sub(new DateInterval("P1D"))->format('j'));

    $weeks = [];
    $indexOfWeek = 0;
    $weekDay = $beginWeekDay;

    for ($day = 1; $day <= $endMonthDay; $day++){
        if (!isset($weeks[$indexOfWeek])){
            $weeks[$indexOfWeek] = [];
        }

        $weeks[$indexOfWeek][] = $day;

        $weekDay++;
        if ($weekDay > 7){
            $weekDay = $weekDay - 7;
            $indexOfWeek++;
        }
    }

    // 只要一个星期里面的第一天和最后一天?
    foreach ($weeks as &$week) {
        $week = [$week[0], end($week)];
    }

    return $weeks;
}

// 测试一下:
foreach (getWeeksOfMonth() as $week){
    echo implode(", ", $week) . "\n";
}

// 输出:(今天是2017-03-08)
// 1, 5
// 6, 12
// 13, 19
// 20, 26
// 27, 31
// 


用到的日期时间API比较少,应该比较高效吧

print_r(date('Y-m-d', strtotime('first mon of january'))); 

参考:http://uk3.php.net/manual/zh/...

for($i=1;$i<=52;$i++){
    $month = ($i < 10) ? '0'.$i : $i;
    echo '第'.$i.'周开始:';
    $monday = date('Y-m-d', strtotime('2017W'.$month));
    echo $monday;
    echo '第'.$i.'周结束:';
    $sunday = date('Y-m-d' ,strtotime($monday . '+6day'));
    echo $sunday;
    echo '<br>';
}

输出:

第1周开始:2017-01-02第1周结束:2017-01-08
第2周开始:2017-01-09第2周结束:2017-01-15

第3周开始:2017-01-16第3周结束:2017-01-22
第4周开始:2017-01-23第4周结束:2017-01-29
第5周开始:2017-01-30第5周结束:2017-02-05
第6周开始:2017-02-06第6周结束:2017-02-12
第7周开始:2017-02-13第7周结束:2017-02-19
第8周开始:2017-02-20第8周结束:2017-02-26
第9周开始:2017-02-27第9周结束:2017-03-05

再次修改:

$months = [
    'january','february','march','april','may','june','july','august ','september','october','november','december'
];
$weeks = [
    '1'=>'first','2'=>'second','3'=>'third','4'=>'fourth'
];
foreach($months as $key=>$value){
    echo $value.'<br>';
    for($i=1;$i<=4;$i++){
        echo '第'.$i.'周:';
        $monday = date('Y-m-d', strtotime($weeks[$i].' monday of '.$value));
        $sunday = date('Y-m-d' ,strtotime($monday . '+6day'));
        echo 'from '.$monday .' to '.$sunday;
        echo '<br>';
    }
}

january
第1周:from 2017-01-02 to 2017-01-08
第2周:from 2017-01-09 to 2017-01-15
第3周:from 2017-01-16 to 2017-01-22
第4周:from 2017-01-23 to 2017-01-29
february
第1周:from 2017-02-06 to 2017-02-12
第2周:from 2017-02-13 to 2017-02-19
第3周:from 2017-02-20 to 2017-02-26
第4周:from 2017-02-27 to 2017-03-05

找到了一个[方法]
你看下是不是你要的效果

function get_weekinfo($month){
    $weekinfo = array();
    $end_date = date('d',strtotime($month.' +1 month -1 day'));
    for ($i=1; $i <$end_date ; $i=$i+7) { 
        $w = date('N',strtotime($month.'-'.$i));
 
        $weekinfo[] = array(date('Y-m-d',strtotime($month.'-'.$i.' -'.($w-1).' days')),date('Y-m-d',strtotime($month.'-'.$i.' +'.(7-$w).' days')));
    }
    return $weekinfo;
}
print_r(get_weekinfo('2013-11'));
 
//执行结果
Array    
(    
   [0] => Array    
       (    
           [0] => 2013-11-25    
           [1] => 2013-12-01    
       )    
   [1] => Array    
       (    
           [0] => 2013-12-02    
           [1] => 2013-12-08    
       )    
   [2] => Array    
       (    
           [0] => 2013-12-09    
           [1] => 2013-12-15    
       )    
   [3] => Array    
       (    
           [0] => 2013-12-16    
           [1] => 2013-12-22    
       )    
   [4] => Array    
       (    
           [0] => 2013-12-23    
           [1] => 2013-12-29    
       )    
)

function weeks($year, $week){
    $year_start = mktime(0,0,0,1,1,$year);
    $year_end = mktime(0,0,0,12,31,$year);
    $weekday = [];
    if (intval(date('w',$year_start)) == 1){
        $start = $year_start;
    }else{
        $start = strtotime('+1 monday',$year_start);
    }

    if ($week == 1){
        $weekday['start'] = $start;
    }else{
        $weekday['start'] = strtotime('+'.($week-0).' monday',$start);
    }

    $weekday['end'] = strtotime('+1 sunday',$weekday['start']);
    if (date('Y',$weekday['end']) != $year){
        $weekday['end'] = $year_end;
    }
    return array_map(function($s){
        return date('Y-m-d',$s);
    },$weekday);
}

>>> weeks(2017,10)
=> [
       "start" => "2017-03-06",
       "end"   => "2017-03-12"
   ]
>>> weeks(2017,1)
=> [
       "start" => "2017-01-02",
       "end"   => "2017-01-08"
   ]
AprMay
  • 2
新手上路,请多包涵
//需要的数组注释掉了
<?php
class GetWeeksOfMonths
{
    public $_month;

    public $_week =array( '1'=>'first','2'=>'second','3'=>'third','4'=>'fourth','5'=>'fifth');

    public $_months = array('january','february','march','april','may','june','july','august ','september','october','november','december');
    public function __construct($month)
    {
        header('Content-Type:text/html;charset:utf-8');
    
        $this->_month = $this->_months[$month];

    }
    //return array
    public function get_weeks_of_months()
    {
        $week = $this->get_total_weeks();
        //$total = array();
        for($i=1;$i<=$week;$i++)
        {
            if($i==$week)
            {
                $start ='第 '.$i.' 周: ';
                $monday =  date('Y-m-d', strtotime( $this->_week[$i].' monday of '.$this->_month));
                $sunday =  date('Y-m-d', strtotime('last day of '.$this->_month));
            }
            else
            {
                $start ='第 '.$i.' 周: ';
                $monday =  date('Y-m-d', strtotime( $this->_week[$i].' monday of '.$this->_month));
                $sunday =  date('Y-m-d', strtotime( $monday.' +6 day'));
            }
            
            $total[]=$monday.' to '.$sunday;
            
            echo $start.$monday.' to '.$sunday.'<br/>';
            
        }
        //print_r($total);
        
        
    } 
    public function get_total_weeks()
    {
        $first_monday = date('Y-m-d', strtotime('first monday of '.$this->_month));
        $last_monday = date('Y-m-d', strtotime('last monday of '.$this->_month));
        $total_weeks =(strtotime($last_monday)-strtotime($first_monday))/(7*24*60*60)+1;
        return $total_weeks;
    }
}


$a = new GetWeeksOfMonths(1);

$a->get_weeks_of_months();

?>
``

![图片描述][1]

宣传栏