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.
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.
I use this method.
public static Integer getQuarter(Date d){
Calendar c = Calendar.getInstance();
c.setTime(d);
int month = c.get(Calendar.MONTH);
return (month /3)+1;
}
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.
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).
Make sure that the thisMonth
is at least a float or a double, not an int:
String quarter = thisMonth/3 <= 1 ? "Q1" : thisMonth/3 <= 2 ? "Q2" : thisMonth/3 <= 3 ? "Q3" : "Q4";
Regards, MS
int month = Calendar.getInstance().get( Calendar.MONTH ) + 1;
int quarter = month % 3 == 0? (month / 3): ( month / 3)+1;