This post shows how to come up with the first and last dates of the current quarter using Joda time. Although we can do it in Java 8 and above using the Time API, Joda Time is an alternative.
Joda Time, JDK, and IDE Requirements
We use the following items in this post.
- Intellij 2022.1 (Ultimate Edition)
- Java Development Kit 17
Next, we update the pom.xml to include the following dependency. Note that this version of the Joda time requires at least JDK 17 to work.
1 2 3 4 5 6 | <!-- https://mvnrepository.com/artifact/joda-time/joda-time --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.14</version> </dependency> |
Java Codes To Get First And Last Dates In The Current Quarter
Then, we craft codes to use Joda time to get the first and last dates in the current quarter. It has one static method that returns an array with two dates. Also, the date with index 0 represents the first date in the quarter while the other represents the other date.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | package com.example.jodatime; import org.joda.time.LocalDate; public class ThisQuarter { public static LocalDate[] getQuarterStartEndDates(LocalDate localDate) { LocalDate[] dates = new LocalDate[2]; // Get the month of the current date int i = localDate.getMonthOfYear(); // 1st - 3rd months represent quarter 1 // 4th - 6th months represent quarter 2 // 7th - 9th months represent quarter 3 // 10th - 12th months represent quarter 4 int startI = 0; int endI = 0; if (i >= 1 && i <= 3) { startI = i - 1; endI = i - 3; } else if (i >= 4 && i <= 6) { startI = i - 4; endI = i - 6; } else if (i >= 7 && i <= 9) { startI = i - 7; endI = i - 9; } else if (i >= 10 && i <= 12) { startI = i - 10; endI = i - 12; } startI = Math.abs(startI); endI = Math.abs(endI); dates[0] = localDate.minusMonths(startI).dayOfMonth().withMinimumValue(); dates[1] = localDate.plusMonths(endI).dayOfMonth().withMaximumValue(); return dates; } } |
Note that we use a class name from Joda time similar to a Java Time API – LocalDate. However, these two classes are different.
Test Joda Time To Get First And Last Dates
Consider the following Java main method.
1 2 3 4 5 6 7 8 9 10 11 | package com.example.jodatime; import org.joda.time.LocalDate; public class JodaTimeApplication { public static void main(String[] args) { LocalDate[] quarterStartEndDates = ThisQuarter.getQuarterStartEndDates(LocalDate.now()); System.out.println(quarterStartEndDates[0]); System.out.println(quarterStartEndDates[1]); } } |
When we run all the codes, we get the following output.
1 2 | 2022-04-01 2022-06-30 |
And that is how we get the first and last dates in the current quarter using Joda Time.