get startdate and enddate for current quarter php

前端 未结 19 1550
悲哀的现实
悲哀的现实 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:40

    I glimpsed over answers and all are about quarters of this year. Sometimes, you need quarter for particular date. Here is my attempt with detailed explanation what-does-what in code comments:

    /**
         * get quarter begin/end date
         * 
         * possible usage:
         * quarter start date: quarter('2016-04-12')[start] - result: 2016-04-01
         * quarter end date: quarter('2016-04-12')[end] - result: 2016-06-30
         * quarter number: quarter('2016-04-12')[number] - result: 2
         * 
         * @param  string   $time   date you want quarter begin and end for - accepted formats, at least: 'Y-m', but also: 'Y-m-d', 'Y-m-d H:i:s' etc.
         * @return array    [quarter start, quarter end, quarter number]
         */
        public function quarter($time)
        {
            /**
             * get quarter number for given date
             * we are ceiling floating point value, so I use (int) casting to get just integer (without decimal part)
             * round() could be used instead of casting to (int)
             */
            $quarter = (int)ceil(date("m", strtotime($time)) / 3);
            $year = date("Y", strtotime($time));
    
            $quarters = [
                1 => ['01-01', '03-31', 1],
                2 => ['04-01', '06-30', 2],
                3 => ['07-01', '09-30', 3],
                4 => ['10-01', '12-31', 4],
            ];
    
            $quarterStart = $year . '-' . $quarters[$quarter][0];
            $quarterEnd = $year . '-' . $quarters[$quarter][1];
            $quarterNumber = $quarters[$quarter][2];
    
            return ['start' => $quarterStart, 'end' => $quarterEnd, 'number' => $quarterNumber];
        }
    

提交回复
热议问题