get startdate and enddate for current quarter php

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

    This was my solution.

    function getCurrentQuarter($timestamp=false){
        if(!$timestamp)$timestamp=time();
        $day = date('n', $timestamp);
        $quarter = ceil($day/3);
        return $quarter;
    }
    
    function getPreviousQuarter($timestamp=false){
        if(!$timestamp)$timestamp=time();
        $quarter = getCurrentQuarter($timestamp) - 1;
        if($quarter < 0){
            $quarter = 4;
        }
        return $quarter;
    }
    
    function getNextQuarter($timestamp=false){
        if(!$timestamp)$timestamp=time();
        $quarter = getCurrentQuarter($timestamp) + 1;
        if($quarter > 4){
            $quarter = 0;
        }
        return $quarter;
    }
    
    function getFirstAndLastDayOfQuarter($quarter, $year=false){
        if(!$year)$year=date('Y');
        $startDate = new DateTime($year.'-'.($quarter*3-2).'-1');
        //Get first day of first month of next quarter
        $endMonth = $quarter*3+1;
        if($endMonth>12){
            $endMonth = 1;
            $year++;
        }
        $endDate = new DateTime($year.'-'.$endMonth.'-1');
        //Subtract 1 second to get last day of prior month
        $endDate->sub(new DateInterval('PT1S'));
        return array($startDate, $endDate);
    }
    

提交回复
热议问题