-
-
Save jetsuit/0be5b048fe680d9b001673a635b81bb8 to your computer and use it in GitHub Desktop.
Get a list of (date) quarters between two given dates. Return array of objects with information about each quarter
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
/** | |
* Class DateQuartersUtil | |
* @package UtilsBundle\Classes | |
*/ | |
class DateQuartersUtil | |
{ | |
/** | |
* Return quarters between tow dates. Array of objects | |
* @param $start_date | |
* @param $end_date | |
* @return array | |
*/ | |
public static function getQuarters($start_date, $end_date){ | |
$quarters = array(); | |
$startMonth = date( 'm', strtotime($start_date) ); | |
$startYear = date( 'Y', strtotime($start_date) ); | |
$endMonth = date( 'm', strtotime($end_date) ); | |
$endYear = date( 'Y', strtotime($end_date) ); | |
$startQuarter = ceil($startMonth/3); | |
$endQuarter = ceil($endMonth/3); | |
$quarter = $startQuarter; // variable to track current quarter | |
// Loop over years and quarters to create array | |
for( $y = $startYear; $y <= $endYear; $y++ ){ | |
if($y == $endYear) | |
$maxQtr = $endQuarter; | |
else | |
$maxQtr = 4; | |
for($q=$quarter; $q<=$maxQtr; $q++){ | |
$currentQuarter = new \stdClass(); | |
$endMonthNum = self::zeroPad($q * 3); | |
$startMonthNum = ($endMonthNum - 2); | |
$qStartMonth = self::monthName($startMonthNum); | |
$qEndMonth = self::monthName($endMonthNum); | |
$currentQuarter->title = "Q$q ('$y)"; | |
$currentQuarter->description = "Qtr $q ($qStartMonth - $qEndMonth) $y"; | |
$currentQuarter->start = "$y-$startMonthNum-01"; // yyyy-mm-dd | |
$currentQuarter->end = "$y-$endMonthNum-" . self::monthEndDate($y, $endMonthNum); | |
$quarters[] = $currentQuarter; | |
unset($currentQuarter); | |
} | |
$quarter = 1; // reset to 1 for next year | |
} | |
return $quarters; | |
} | |
/** | |
* get month name from number | |
* @param $monthNumber | |
* @return false|string | |
*/ | |
protected static function monthName($monthNumber){ | |
return date('F', mktime(0, 0, 0, $monthNumber, 10)); | |
} | |
/** | |
* get get last date of given month (of year) | |
* @param $year | |
* @param $monthNumber | |
* @return false|string | |
*/ | |
protected static function monthEndDate($year, $monthNumber){ | |
return date("t", strtotime("$year-$monthNumber-1")); | |
} | |
/** | |
* return two digit month or day, e.g. 04 - April | |
* @param $number | |
* @return string | |
*/ | |
protected static function zeroPad($number){ | |
if($number < 10) { | |
return "0$number"; | |
} | |
return "$number"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment