find specific weeks in month using php

前端 未结 2 1579
南笙
南笙 2020-12-22 07:14

I am tring to get the week from the month having starting Monday and end with Sunday with in same month. i\'ll provide month and year. for example:

$month =          


        
相关标签:
2条回答
  • 2020-12-22 07:26

    You can use the DateTime class for this:

    $dt = new DateTime('1st march');
    
    // is this a monday?
    if($dt->format('N') !== '1') {
      // if not, went to next monday
      $dt->modify('next monday');
    }
    
    echo $dt->format('Y-m-d')
        . ' to ' . $dt->modify('next sunday')->format('Y-m-d');
    

    Output:

    2014-03-03 to 2014-03-09
    
    0 讨论(0)
  • 2020-12-22 07:31
    <?php
    function get_weeks($month, $year) {
        $weeks = array();
    
        $date = DateTime::createFromFormat('mY', $month.$year);
        $date->modify('first Monday of this month');
    
        $end = clone $date;
        $end->modify('last Monday of this month');
        $interval = DateInterval::createFromDateString('1 week');
        $period = new DatePeriod($date, $interval, $end);
    
        $counter = 1;
        foreach ($period as $dt) {
            $end_of_week = clone $dt;
            $end_of_week->modify('next Sunday');
            $weeks[] = sprintf("Week %u: %s - %s", 
                $counter,
                $dt->format('Y-m-d'),
                $end_of_week->format('Y-m-d')
            );      
            $counter++;
        }
    
        return $weeks;
    }
    $weeks = get_weeks('03', '2014');
    print_r($weeks);
    
    Array
    (
        [0] => Week 1: 2014-03-03 - 2014-03-09
        [1] => Week 2: 2014-03-10 - 2014-03-16
        [2] => Week 3: 2014-03-17 - 2014-03-23
        [3] => Week 4: 2014-03-24 - 2014-03-30
    )
    

    See it in action

    0 讨论(0)
提交回复
热议问题