Split date ranges into corresponding weeks

date, mysql, php

Solution

This snippet uses Sunday as the first day of the week:

    $start = new DateTime('2014-10-01');
    $end = new DateTime('2014-10-31 23:59');
    $interval = new DateInterval('P1D');
    $dateRange = new DatePeriod($start, $interval, $end);

    $weekNumber = 1;
    $weeks = array();
    foreach ($dateRange as $date) {
        $weeks[$weekNumber][] = $date->format('Y-m-d');
        if ($date->format('w') == 6) {
            $weekNumber++;
        }
    }

Each week will have all the days in it.

If you just want the first and last days of each week then you can just use `array_shift` and `array_pop` to get them. For example, for the first week you can use:

    $wk1Start = array_shift($weeks[1]); //gives you first day of week 1
    $wk1End = array_pop($weeks[1]); // give you the last day of week 1

If you want the start and end dates for each week, here is a way of doing it:

    $ranges = array_map(function($week) {
        return 'start: ' . array_shift($week) 
            . ', end: ' . array_pop($week); },
    $weeks);

This is the output of `$ranges` for me:

    Array
    (
        [1] => start: 2014-10-01, end: 2014-10-04
        [2] => start: 2014-10-05, end: 2014-10-11
        [3] => start: 2014-10-12, end: 2014-10-18
        [4] => start: 2014-10-19, end: 2014-10-25
        [5] => start: 2014-10-26, end: 2014-10-31
    )

Problem

I have date ranges called from and to.I want to convert it to weeks. Suppose from date is 1-10-2014 and to date is 31-10-2014 Then result is: 1st week : 01-10-2014 to 04-10-2014 2nd : 05-102014 to 11-10-2014 3rd : 12-10-2014 to 18-10-2014 4th : 19-10-2014 to 25-10-2014 5th : 26-10-2014 to 31-10-2014 In php.I try several code but that didn't given the absolute result only give 01 to 7 , 8 to 14 etc. Pls help. I already try answers from ``` Get the date of one week from today with PHP in stack overflow date("Y-m-d",strtotime("+1 week")); ```

Original source