java.time
The modern approach uses the java.time classes. Never use Date
/Calendar
/SimpleDateFormat
and such.
LocalDate
The LocalDate
class represents a date-only value, without time-of-day and without time zone.
LocalDate startLocalDate = LocalDate.of( 2011 , Month.DECEMBER , 20 ) ;
LocalDate stopLocalDate = LocalDate.of( 2012 , Month.AUGUST , 2 ) ;
YearMonth
When interested only in the year and month, use the class YearMonth
.
YearMonth start = YearMonth.from( startLocalDate) ;
YearMonth stop = YearMonth.from( stopLocalDate ) ;
Loop.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM/uuuu" , Locale.US ) ;
int initialCapacity = start.until( stop , ChronoUnit.MONTHS ) ;
List< YearMonth > yearMonths = new ArrayList<>( initialCapacity ) ;
YearMonth ym = start ;
while ( ym.isBefore( stop ) ) {
System.out.println( ym.format( f ) ) ; // Output your desired text.
yearMonths.add( ym ) ;
ym = ym.plusMonths( 1 ) ; // Increment to set up next loop.
}
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
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.