tags:

views:

2043

answers:

5

Given a java.util.Date object how do I go about finding what Quarter it's in?

Assuming Q1 = Jan Feb Mar, Q2 = Apr, May, Jun, etc.

+6  A: 

You could use

int quarter = (myDate.getMonth() / 3) + 1;

Be warned, though that getMonth is deprecated:

As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH).

Bill the Lizard
Month is zero-based, so December = 11. 11 / 4 + 1 = 3. Do the dimensional analysis: MONTH / x = QUARTER so x = MONTHS / QUARTER, not QUARTER / YEAR.
erickson
I was just looking that over as you posted this comment.
Bill the Lizard
NP, you made me doubt my math for a second ;)
erickson
LOL, sorry. I felt really silly after I discovered I made an off by one error.
Bill the Lizard
+2  A: 

You are going to have to write your own code because the term "Quarter" is different for each business. Can't you just do something like:

Calendar c = /* get from somewhere */
int month = c.get(Calendar.MONTH);

return (month >= Calendar.JANUARY && month <= Calendar.MARCH)     ? "Q1" :
       (month >= Calendar.APRIL && month <= Calendar.JUNE)        ? "Q2" :
       (month >= Calendar.JULY && month <= Calendar.SEPTEMBER)    ? "Q3" :
                                                                    "Q4";
Outlaw Programmer
A: 

Since quarters are a localized (Western) concept, specify a Locale rather than using the platform default:

Calendar cal = Calendar.getInstance(Locale.US);
/* Consider whether you need to set the calendar's timezone. */
cal.setTime(date);
int month = cal.get(Calendar.MONTH); /* 0 through 11 */
int quarter = (month / 3) + 1;

This will avoid getting the thirteenth month (Calendar.UNDECIMBER) on non-Western calendars, and any skew caused by their shorter months.

erickson
Lousy Smarch weather!
Outlaw Programmer
I was thinking that!
xan
A: 

JFreeChart has a Quarter class. If you're curious, check out the javadoc. The source is also available from SourceForge if you want to check out the implementation.

bcash
+1  A: 

Good solutions here, but remember that quarters can be subject to change depending on company/industry too. Sometimes a quarter can be a different 3 months.

You probably want to extend or encapsulate the calendar class to customize it to your tasks rather than write some utility function that converts it. Your application is probably complex enough in that area that you will find other uses for your new calendar class--I promise you'll be glad you extended or encapsulated it even if it seems silly now.

Bill K