Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I discover the Quarter of a given Date?

Tags:

java

calendar

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.

like image 656
Allain Lalonde Avatar asked Nov 19 '08 17:11

Allain Lalonde


People also ask

How do I calculate a quarter to date?

How Does Quarter to Date (QTD) Work? By adding the revenue for the three months of the first quarter, we can calculate that Company XYZ's quarter-to-date revenue is $4,500,000.

How to get quarter date in Java?

get(Calendar. MONTH) and int quarter = (month / 3)+1; Oh wait, that's the accepted answer.


1 Answers

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; 
like image 63
Bill the Lizard Avatar answered Sep 19 '22 07:09

Bill the Lizard