Last active
March 6, 2020 10:29
Divide date interval to subintervals.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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):