How do I discover the Quarter of a given Date?

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";

Since Java 8, the quarter is accessible as a field using classes in the java.time package.

import java.time.LocalDate;
import java.time.temporal.IsoFields;

LocalDate myLocal = LocalDate.now();
quarter = myLocal.get(IsoFields.QUARTER_OF_YEAR);

In older versions of Java, you could use:

import java.util.Date;

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

Be warned, though that getMonth was deprecated early on:

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

Instead you could use a Calendar object like this:

import java.util.Calendar;
import java.util.GregorianCalendar;

Calendar myCal = new GregorianCalendar();
int quarter = (myCal.get(Calendar.MONTH) / 3) + 1;

In Java 8 and later, the java.time classes have a more simple version of it. Use LocalDate and IsoFields

LocalDate.now().get(IsoFields.QUARTER_OF_YEAR)

Tags:

C#

Java

Calendar