Skip to content
Advertisement

Algorithm to create X number of dates

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:

JavaScript

Output:

JavaScript

Learn more about the modern date-time API at Trail: Date Time.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement