質問

I am trying to make a function that gives me the number of quarters between 2 dates as an integer. The dates passed to the function are usually quarter-end dates except occasionally when one of the dates is just an arbitary date.

Basically I want it to figure out what quarter the two dates fall into and give an integer difference in the number of quarters.

E.g.

Q1 2013 -> Q2 2013 = 1
Q1 2013 -> Q4 2013 = 3 
Q2 2012 -> Q2 2013 = 4
Q4 2012 -> Q1 2013 = 1

Here is my function. I realise it is poor and does not return the correct answer all the time but I'm hoping someone can help...

function quarter_diff(DateTime $d1, DateTime $d2){
    //difference in months
    $diff = $d1->diff($d2);

    return ceil((($diff->format('%y') * 12) + $diff->format('%m')+1)/4);
}

and a fiddle here: http://phpfiddle.org/lite/code/tiw-jx3

We can see theat when the date is in the month after the end of a quarter we don not get the correct answer.

Can anyone suggest an improvement??

役に立ちましたか?

解決

Convert each of your dates into quarters, then do the math, much like your first example. Some quick pseudocode:

Convert d1 to quarter and year -> d1.quarter and d1.year
Convert d2 to quarter and year -> d2.quarter and d2.year
Number of quarters = d1.quarter - d2.quarter + (d1.year - d2.year)*4

Use the absolute value of the result to get the number of quarters difference.

You can create a quick and dirty "quarter" function by dividing month-1 by 3 and adding 1 to the integer portion of the result. Assuming January = 1, December = 12 and Q1 = January through March. You'll have to make adjustments if Q1 starts elsewhere, such as July.

Q = (int)(month - 1)/3 + 1
or
Q = ceiling(month/3)

他のヒント

This is what I opted for thanks to suggestion from Maple

function quarter_diff(DateTime $d1, DateTime $d2){
    //Returns the number of quarters between two dateTime objects
    if ($d2 > $d1){
        $dtmp = $d1;
        $d1=$d2;
        $d2=$dtmp;
        unset($dtmp);
    }
    $d1q = ceil($d1->format('m')/3);
    $d2q = ceil($d2->format('m')/3);
    $d1y = $d1->format('y');
    $d2y = $d2->format('y');

    return $d1q - $d2q + 4*($d1y - $d2y);
} 

in MYSQL:

SELECT (year('2016-06-30') - year('2015-07-01'))*4 + quarter('2016-06-30') - quarter('2015-07-01') + 1 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top