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)