Skip to content

Instantly share code, notes, and snippets.

@itorgov
Last active March 6, 2020 10:29
Show Gist options
  • Save itorgov/fdeb793d5612fc859a0b3b1c72f85d6c to your computer and use it in GitHub Desktop.
Save itorgov/fdeb793d5612fc859a0b3b1c72f85d6c to your computer and use it in GitHub Desktop.
Divide date interval to subintervals.
<?php
class DateService
{
const ONE_WEEK_INTERVAL = '+6 days';
const THIRTY_DAYS_INTERVAL = '+29 days';
const ONE_YEAR_INTERVAL = '+364 days';
/**
* This method get two dates (start and end of an interval) and length of every subinterval you need.
*
* @param DateTime $startDate Start of an original interval.
* @param DateTime $endDate End of an original interval.
* @param string $intervalSize Length of every subinterval (use constants, please).
*
* @return array
*/
public static function getSubIntervals(DateTime $startDate, DateTime $endDate, $intervalSize)
{
$dates = [];
while (true) {
$firstDate = clone($startDate);
$startDate->modify($intervalSize);
$secondDate = clone($startDate);
$dates[] = [
'start' => $firstDate,
'end' => $secondDate >= $endDate ? $endDate : $secondDate
];
$startDate->modify('+1 days');
if ($firstDate >= $endDate || $secondDate >= $endDate) {
break;
}
}
return $dates;
}
}
@itorgov
Copy link
Author

itorgov commented Aug 25, 2016

Example output of this method. For example, you have an interval with start 2016-08-01 and end 2016-08-31. Then you want to divide it to subintervals and every subinterval have to have 7 days in length. So, we can use constant ONE_WEEK_INTERVAL for that. Final, we will get this array which will contain start and end dates of every subinterval (note that in example below dates are strings, but method returns dates in DateTime objects):

[
    [
        'start' => '2016-08-01',
        'end' => '2016-08-07'
    ],
    [
        'start' => '2016-08-08',
        'end' => '2016-08-14'
    ],
    [
        'start' => '2016-08-15',
        'end' => '2016-08-21'
    ],
    [
        'start' => '2016-08-22',
        'end' => '2016-08-28'
    ],
    [
        'start' => '2016-08-29',
        'end' => '2016-08-31'
    ]
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment