get startdate and enddate for current quarter php

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

    You can simply this greatly using basic math.

    Each Month number minus 1 % 3 will tell how many months you are offset from the current quarter..

    /**
     * @param DateTime $date
     * @return array
     */
    function getQuarterRangeFromDate(DateTime $date)
    {
    
        // Clone the date to avoid modifying your date in current context
        $quarter_start = clone($date);
    
        // Find the offset of months
        $months_offset = ($date->format('m') - 1) % 3;
    
    
        // Modify quarter date
        $quarter_start->modify(" - " . $months_offset . " month")
            ->modify("first day of this month");
    
    
        $quarter_end = clone($quarter_start);
        $quarter_end->modify("+ 3 month");
    
        return [$quarter_start, $quarter_end];
    }
    

提交回复
热议问题