tl;dr
YearQuarter.from( LocalDate.parse( "2017-06-30" ) )
.plusQuarters( 1 )
org.threeten.extra.YearQuarter
The other Answer by Ole V.V. using java.time is good. Alternatively, here is code using the YearQuarter
class from the ThreeTen-Extra project that extends java.time with additional functionality. If you are doing much work with quarters, you will find it well worth the bother to add the ThreeTen-Extra library to your project.
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate start = LocalDate.parse( "2017-06-30" );
LocalDate stop = LocalDate.parse( "2017-12-31" );
From those, determine the year-quarter in the ISO 8601 calendar system, meaning Q1 is January to March, Q2 is April to June, Q3 is July to September and Q4 is October to December.
YearQuarter yqStart = YearQuarter.from( start );
YearQuarter yqStop = YearQuarter.from( stop );
Collect the series of quarters as a List
.
int initialCapacity = ( int ) ( ChronoUnit.YEARS.between( start , stop ) + 1 ) * 4;
List < YearQuarter > quarters = new ArrayList <>( initialCapacity );
Loop each quarter, incrementing by calling plusQuarters
, and collect into the list.
YearQuarter yq = yqStart;
while ( ! yq.isAfter( yqStop ) )
{
quarters.add( yq );
// Setup next loop.
yq = yq.plusQuarters( 1 );
}
Dump to console.
System.out.println( start + "/" + stop + " = " + quarters );
2017-06-30/2017-12-31 = [2017-Q2, 2017-Q3, 2017-Q4]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.