I am trying to set a start date and end date by the quarter.
For example, I am working on a reporting system where i need to report data for quarter 1, quarter 2, qu
Simple code:
$current_quarter = ceil(date('n') / 3);
$first_date = date('Y-m-d', strtotime(date('Y') . '-' . (($current_quarter * 3) - 2) . '-1'));
$last_date = date('Y-m-t', strtotime(date('Y') . '-' . (($current_quarter * 3)) . '-1'));
This could be a whole lot simpler I think.
function get_this_quarter() {
$current_month = date('m');
$current_quarter_start = ceil($current_month/4)*3+1; // get the starting month of the current quarter
$start_date = date("Y-m-d H:i:s", mktime(0, 0, 0, $current_quarter_start, 1, date('Y') ));
$end_date = date("Y-m-d H:i:s", mktime(0, 0, 0, $current_quarter_start+3, 1, date('Y') ));
// by adding or subtracting from $current_quarter_start within the mktime function you can get any quarter of any year you want.
return array($start_date, $end_date);
}
This works just as good without all the if statements and is much more flexible. As mentioned in the comments within the code, you can easily modify the $current_quarter_variable to suit your needs.
Hope this helps!
what about:
$offset = (date('n')%3)-1; // modulo ftw
$start = new DateTime("first day of -$offset month midnight");
$offset = 3-(date('n')%3); // modulo ftw again
$end = new DateTime("last day of +$offset month midnight");
function getDates( $passedDate = '' ) {
if( $passedDate == '' ) {
$v = ceil( date( "m" ) / 3 );
$y = date( "Y" );
} else {
$v = ceil( $month / 3 );
$y = date( "Y", strtotime( $passedDate ) );
}
$y = date( "Y" );
$m = ( $v * 3 ) - 2;
$date = $y . '-' . $m . '-' . 01;
$return['begin'] = date( "Y-m-d", strtotime( $date ) );
$return['end'] = date( "Y-m-t", strtotime( $return['begin'] . "+ 2 months" ) );
$return['version'] = $y . 'Q' . ceil( date( "m" ) / 4 );
return $return;
}
This Function will return starting and end date and quarter for current date by default, however if you want it for particular date just pass month to it.
I needed some function to give me dates for each quarter so I could fetch some sales info. Here is the code if anyone needs it:
private function getQuarterRange($quarter, $year=null) {
if ($quarter > 4 || $quarter < 1)
return null;
if ($year == null)
$year = date('Y');
$startDate = date('Y-m-d', strtotime($year . '-' . (($quarter * 3) - 2). '-1'));
$endDate = date('Y-m-d', strtotime(date('Y-m-d', strtotime($startDate)) . '+3 month - 1 day'));
return ['startDate' => $startDate, 'endDate' => $endDate];
}
Simply call: var_dump($this->getQuarterRange(4, 2018));
Output:
array(2) {
["startDate"]=>
string(10) "2018-10-01"
["endDate"]=>
string(10) "2018-12-31"
}
A simpler way to get the start/end of the current quarter in dates:
$qtr_start = date("Y-".(ceil(date("n")/3))."-01");
Then, just add 3 months in the correct place to get the end:
$qtr_end = date("Y-".(ceil(date("n")/3)+3)."-01");
Just my two cents.