Home > Software design >  How to get the list of dates in a given range with recursion
How to get the list of dates in a given range with recursion

Time:09-17

I want to create a function that returns a list of dates in the given range, with recursion. I will provide the starting date, the ending date, and the type of recursion. I am not sure how to start. Any suggestions would be helpful. Is there any library for this, or do I have to do it on my own?

data class Date(
    val day: Int,
    val month: Int,
    val year: Int
)

enum class Recursion {
    NEVER,
    EVERY_DAY,
    EVERY_WORK_DAY,
    EVERY_WEEK,
    EVERY_MONTH,
    ANNUAL
}

fun createListOfEvents(startDate: Date, endDate: Date, recursion: Recursion): List<Date>{
}

CodePudding user response:

Well, basically this is an example of how you can do this:

data class Recursion(val field : TemporalUnit, val step: Long)

    val step1Day = Recursion(field = ChronoUnit.DAYS, step = 1)

    fun createListOfEvents(startDate: LocalDate, endDate: LocalDate, recursion: Recursion): List<LocalDate>{
        var currentDate = startDate
        val listOfDates = mutableListOf<LocalDate>()
        while (currentDate.isBefore(endDate)) {
            listOfDates.add(currentDate)
            currentDate = startDate.plus(recursion.step, recursion.field)
        }
        return listOfDates
    }

This method returns list of dates from startDate until endDate with the step of Recursion. As you can see I've used java.time.* classes for this, but eventually you can convert them into your own Date and Recursion and back. Here TemporalUnit can be DAYS, WEEKS, MONTHS, YEARS (and other). It covers most of your needs, working days you will have to manage manually. Hope this makes sense )

CodePudding user response:

You need to enable desugaring if targeting SDK < 26.

Then you can use the LocalDate class for this. Your Date class is kind of redundant, but you could convert inside the function to LocalDate if you want to keep it.

fun createListOfEvents(startDate: LocalDate, endDate: LocalDate, recursion: Recursion): List<LocalDate> {
    val step = when (recursion) {
        Recursion.NEVER -> return emptyList()
        Recursion.EVERY_DAY, Recursion.EVERY_WORK_DAY -> Period.ofDays(1)
        Recursion.EVERY_WEEK -> Period.ofWeeks(1)
        Recursion.EVERY_MONTH -> Period.ofMonths(1)
        Recursion.ANNUAL -> Period.ofYears(1)
    }
    var date = startDate
    val list = mutableListOf<LocalDate>()
    while (date <= endDate) {
        list.add(date)
        date  = step
    }
    if (recursion == Recursion.EVERY_WORK_DAY) {
        val weekend = listOf(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY)
        list.removeAll { it.dayOfWeek in weekend }
    }
    return list
}
  • Related