Currently I have a list of Strings that represent a date in a yyyyMM format, something like this:
- 202008
- 202009
- 202010
I need to create x number of entries in this list with each entry increasing the month by one, so if I were to create 3 new entries they would look like this:
- 202011
- 202012
- 202101
Currently my idea is to create a method to pick the latest date, parse the String to separate month and year, increase the month value by 1 if it is < 12 otherwise set it to 1 and increase the year instead. Then I would add that value to a list and set it as the most recent, repeating x number of times.
What I want to know is if there is a more elegant solution that I could use, maybe using an existing date library (I’m using Java).
Advertisement
Answer
YearMonth
And DateTimeFormatter
I recommend you do it using these modern date-time classes as shown below:
import java.time.YearMonth; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { // Test List<String> list = getYearMonths("202011", 3); System.out.println(list); // Bonus: Print each entry of the obtained list, in a new line list.forEach(System.out::println); } public static List<String> getYearMonths(String startWith, int n) { List<String> list = new ArrayList<>(); // Define Formatter DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMM"); // Parse the year-month string using the defined formatter YearMonth ym = YearMonth.parse(startWith, formatter); for (int i = 1; i <= n; i++) { list.add(ym.format(formatter)); ym = ym.plusMonths(1);// Increase YearMonth by one month } return list; } }
Output:
[202011, 202012, 202101] 202011 202012 202101
Learn more about the modern date-time API at Trail: Date Time.