Skip to content
Advertisement

Get time period ( hour / half-hour / quarter hour ) of day

Is there any way to download every hour and another period of the day? I mean exactly the result in the form of a list.

[
"00:00", // start of the day e.q 14.03
"01:00",
"02:00",
....
"23:00",
"00:00  // end of the day e.q 14.03
]

and

[
"00:00", // start of the day e.q 14.03
"00:30",
"01:00"
"01:30"
....
"00:00  // end of the day e.q 14.03
]

and

[
"00:00", // start of the day e.q 14.03
"00:15",
"00:30"
"00:45"
"01:00"
....
"00:00  // end of the day e.q 14.03
]

14.03 means March 14 for the sake of the example.

Of course it is possible to add this manually, but it would not be a particularly elegant solution. Is it possible to do it without explicitly declaring constants as values of each hour ? The best solution would be a function without using loops and if else constructions.

I have not yet been able to find an implementation of such a solution. I myself also spend another hour on this without success. I need it to implement a functionality that creates a Map or a list of pairs from a list of such e.q hours:

[
"00:00 - 01:00",
"01:00 - 02:00",
"02:00 - 03:00 "
//.......
"23:00 - 00:00"
]

Has anyone had occasion to implement such a problem and would be able to help?

Advertisement

Answer

You could write a function to generate a Sequence<LocalTime> like this:

fun generateTimesOfDay(interval: java.time.Duration) = sequence {
    if (interval > java.time.Duration.ofDays(1)) {
        repeat(2) { yield(LocalTime.MIDNIGHT) }
        return@sequence
    }
    var time = LocalTime.MIDNIGHT
    while (true) {
        yield(time)
        val newTime = time + interval
        if (newTime > time) {
            time = newTime
        } else {
            break // passed or reached midnight
        }
    }
    yield(LocalTime.MIDNIGHT) // Midnight the next day to end last period
}

Then you have all the LocalTimes you can use with toString() or with .format() and some DateTimeFormatter to format them how you like. You can use zipWithNext() to create the time ranges.

val x = generateTimesOfDay(java.time.Duration.ofMinutes(15))
println(x.toList())
println(
    x.zipWithNext { a, b -> "$a - $b" }.toList()
)

Note, I’m using fully qualified java.time.Duration to avoid conflicts with the Kotlin standard library Duration class.

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