Skip to content
Advertisement

How to take dynamic Monday of week

$start_date = '2015-09-21';
$end_Date = '2016-09-21';



    function getStartAndEndDate($start_date, $end_Date ){
        $date1 = new DateTime($start_date);
        $date2 = new DateTime($end_Date);
        $interval = $date1->diff($date2);
        
        
        $weeks = floor(($interval->days) / 7);
        $date_differences = array();
        for($i = 1; $i <= $weeks; $i++){    
            $date1->add(new DateInterval('P4D'));
            $s_time = strtotime($start_date);
            $week_number = date('W', $s_time); 
            $date_differences[] = $start_date." - ".$date1->format('Y-m-d')."<br>";
            $date1->add(new DateInterval('P3D'));
            $start_date = $date1->format('Y-m-d');
            }
            
            return $date_differences;
        }

Output of the function is:

    [0] => 2015-09-1 @@ 2015-09-05
    [1] => 2015-09-08 @@ 2015-09-12
    [2] => 2015-09-15 @@ 2015-09-19
    [3] => 2015-09-22 @@ 2015-09-26
    [4] => 2015-09-29 @@ 2015-10-03
    [5] => 2015-10-06 @@ 2015-10-10
    [6] => 2015-10-13 @@ 2015-10-17
    [7] => 2015-10-20 @@ 2015-10-24
    [8] => 2015-10-27 @@ 2015-10-31
    [9] => 2015-11-03 @@ 2015-11-07

In this function, when i give start and end date, it returns me all weeks start and end date but the problem it works perfectly when i gave him start date which is exactly Monday. When i gave it a date which is not on Monday but some other days it simply add four days and makes week like (Tuesday to Saturday). What i exactly want is if someone enters date which is not Monday, it should start its week with Monday. e.g. if

$start_date = '2015-09-21';
$end_Date = '2016-09-21';

it returns output like this:

[0] => 2015-08-31 @@ 2015-09-04
[1] => 2015-09-07 @@ 2015-09-11
[2] => 2015-09-14 @@ 2015-09-18
[3] => 2015-09-21 @@ 2015-09-25

Advertisement

Answer

$date = new DateTime('your date');

$date->modify('-' . $date->format('N')+1 . 'days');

and print the date in which ever format you want 🙂

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement