Home > OS >  List of "Year-Month" from Current Year month to Jan-2021 in Java
List of "Year-Month" from Current Year month to Jan-2021 in Java

Time:02-11

I have a business requirement to write a service which returns the list of Year months (01-2021,02-2021,....) starting from 01-2021 to the current year month (current : 02-2022).

Can anyone suggest me the approach that I can take to solve this in Java 8

O/P : 01-2021, 02-2021, 03-2021, 04-2021 , so on , 02-2022.

CodePudding user response:

The java.time package has a YearMonth class (documentation) ideal for this use case:

for (YearMonth ym = YearMonth.of(2021, Month.JANUARY); // or ...of(2021, 1)
     !ym.isAfter(YearMonth.now());
     ym = ym.plusMonths(1))
{
    System.out.printf("%Tm-%1$TY\n", ym);
}

CodePudding user response:

import java.time.*;
import java.time.format.DateTimeFormatter;
public class YearMonth {
    public static void getYearMonths() {

        YearMonth nextMonth = YearMonth.now().plusMonths(1);
        YearMonth yearMonth = YearMonth.of(2021, 01);
 
        while (nextMonth.isAfter(yearMonth)) {
        // Create a DateTimeFormatter string
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-yyyy");
        
        // Format this year-month
        System.out.println(yearMonth.format(formatter));
        yearMonth = yearMonth.plusMonths(1);
        }
    }
}

CodePudding user response:

Something like the following would do.

YearMonth now = YearMonth.now();
YearMonth ym = YearMonth.of(2021, 1);
List<YearMonth> list = new ArrayList<>();
while (!ym.isAfter(now)) {
  list.add(ym);
  ym = ym.plusMonths(1);
}

Should get you a list starting from 2021-1 till now.

Another option is to use a stream.

long months = Period.between(LocalDate.of(2021, 1, 1), LocalDate.now()).toTotalMonths();
List<YearMonth> yms = LongStream.rangeClosed(0, months)
  .mapToObj(it -> YearMonth.now().minusMonths(it))
  .collect(Collectors.toList());

You first calculate the number of months, iterate over that number and generate the list.

  • Related