Get Quarter from Date, Quarter Start and End Date in Java

A year has 4 quarters (commonly denoted as Q1, Q2, Q3, and Q4) and each quarter has 3 months. This Java tutorial discusses approaches to obtain the information of the currently running quarter, the start date, and the end date of the current quarter. We will also learn to get the start date and end date of any specific quarter.

1. Get Quarter for a Given Date

The new Java 8 date-time APIs contain a class java.time.temporal.IsoFields having fields (and units) that follow the calendar system based on the ISO-8601 standard. Among these fields, we have a field for our usecase i.e. IsoFields.QUARTER_OF_YEAR.

Let’s see how we can use this field to get the quarter number as an integer value.

LocalDate localDate = LocalDate.now();  // Given date

int currentQuarter = localDate.get(IsoFields.QUARTER_OF_YEAR);  // returns 1, 2, 3 or 4

If we want to get the quarter number in a formatted pattern (Q1, Q2, etc.) for display purposes, we can DateTimeFormatter and the pattern ‘QQQ’.

String currentQuarterStr1 = localDate.format(DateTimeFormatter.ofPattern("QQQ"));
String currentQuarterStr2 = localDate.format(DateTimeFormatter.ofPattern("QQQQ"));

System.out.println(currentQuarterStr1);
System.out.println(currentQuarterStr2);

The program output:

Q1
1st quarter

We can verify from the outputs that we are able to retrieve the current quarter number of the year.

2. Get the Start and End Date of a Quarter

Similar to the previous example, we can use IsoFields.DAY_OF_QUARTER field for accessing the first day and the last date of a quarter also. Let us see with an example.

LocalDate firstDay = localDate.with(IsoFields.DAY_OF_QUARTER, 1L);
LocalDate lastDay = firstDay.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());

System.out.println(firstDay); 
System.out.println(lastDay);  

The program output:

2024-01-01
2024-03-31

This way we can find the start date and end date of the current quarter.

3. Get the Number of Quarters between Two Dates

If we have two LocalDate values and we want to calculate the number of quarters between those dates, we can calculate with the help of IsoFields.QUARTER_YEARS which represents the concept of a quarter-year and can be used as follows:

long quarterCount = IsoFields.QUARTER_YEARS.between(startDate, endDate);

4. Conclusion

This short Java tutorial demonstrated to use of the new Java 8 APIs to obtain the information of the current quarter, as well as the start and end date of the current quarter.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.