How to adopt dynamic monday of the week

Hey guys,

$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;
        }

Function Output:

    [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 the start and end dates, it returns me all the start and end dates of the week, but the problem is that it works fine when I give it the start date, which is exactly on Monday. When I gave him a date that is not on Monday, but on other days, she just adds four days and makes a week like (Tuesday to Saturday). What I definitely want is if someone enters a date that is not Monday, she should start her week from Monday. for example if

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

it returns the output as follows:

[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
+4
source share
2 answers
$date = new DateTime('your date');

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

and print the date on which you want: *

-1
source

, , DateTime:

$s = new DateTime('2016-09-23');
$s->modify('-' . $s->format('N')+1 . 'days');
//2016-09-19
echo $s->format('Y-m-d');
0

Source: https://habr.com/ru/post/1655572/


All Articles