fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. import java.time.* ;
  8. import java.time.temporal.* ;
  9. import java.time.format.* ;
  10.  
  11.  
  12. /* Name of the class has to be "Main" only if the class is public. */
  13. class Ideone
  14. {
  15. public static void main (String[] args) throws java.lang.Exception
  16. {
  17.  
  18. LocalDate startDate = LocalDate.parse( "2017-01-15" ) ;
  19. LocalDate stopDate = LocalDate.parse( "2017-05-27" ) ;
  20.  
  21. YearMonth start = YearMonth.from( startDate ) ;
  22. YearMonth stop = YearMonth.from( stopDate ) ;
  23.  
  24. int initialCapacity = ( (int) ChronoUnit.MONTHS.between( startDate , stopDate ) ) + 1 ; // Adding one for good measure - I didn't really think out this detail.
  25. List< YearMonth > yms = new ArrayList<>( initialCapacity ) ;
  26.  
  27. YearMonth ym = start.plusMonths( 1 ) ; // Add one, to *not* include the first month.
  28. while ( ym.isBefore( stop ) ) { // Do *not* include the last month.
  29. yms.add( ym ) ;
  30. ym = ym.plusMonths( 1 ) ;
  31. }
  32.  
  33. System.out.println("Months between " + startDate + " and " + stopDate + " = " + yms ) ;
  34.  
  35. DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM-uuuu" , Locale.US ) ;
  36. for( YearMonth yearMonth : yms ) {
  37. System.out.println( yearMonth.format( f ) ) ;
  38. }
  39.  
  40.  
  41. }
  42. }
Success #stdin #stdout 0.16s 4575232KB
stdin
Standard input is empty
stdout
Months between 2017-01-15 and 2017-05-27 = [2017-02, 2017-03, 2017-04]
Feb-2017
Mar-2017
Apr-2017