get startdate and enddate for current quarter php

前端 未结 19 1620
悲哀的现实
悲哀的现实 2020-12-29 10:58

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

19条回答
  •  轮回少年
    2020-12-29 11:17

    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!

提交回复
热议问题