php - Difference between 2 dates in quarters -


i trying make function gives me number of quarters between 2 dates integer. dates passed function quarter-end dates except when 1 of dates arbitary date.

basically want figure out quarter 2 dates fall , give integer difference in 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 function. realise poor , not return correct answer time i'm hoping 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 fiddle here: http://phpfiddle.org/lite/code/tiw-jx3

we can see theat when date in month after end of quarter don not correct answer.

can suggest improvement??

convert each of dates quarters, then math, first example. quick pseudocode:

convert d1 quarter , year -> d1.quarter , d1.year convert d2 quarter , year -> d2.quarter , d2.year number of quarters = d1.quarter - d2.quarter + (d1.year - d2.year)*4 

use absolute value of result number of quarters difference.

you can create quick , dirty "quarter" function dividing month-1 3 , adding 1 integer portion of result. assuming january = 1, december = 12 , q1 = january through march. you'll have make adjustments if q1 starts elsewhere, such july.

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

Comments