'List of "Year-Month" from Current Year month to Jan-2021 in Java
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.
Solution 1:[1]
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);
}
Solution 2:[2]
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);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Geeth |
