Home > Net >  How to generate a time range seq by step in Scala?
How to generate a time range seq by step in Scala?

Time:10-14

Here is my demand:

startAt: LocalDateTime(...)
endAt: LocalDateTime(...)
interval: Int

generate a seq, which like this:

Seq(startAt -> startAt.plusHours(interval), ... , startAt.plusMultHours() -> endAt)

Now, I was convert the LocalDateTime to unix(Long) and use Range to complete this, is there any better way?

Thanks a lot!

CodePudding user response:

You can get differens in hours between two dates, create an range and map it:

val result = (0L to ChronoUnit.HOURS.between(startAt, endAt) by interval)
    .map(startAt.plusHours(_))

CodePudding user response:

Is this suit for you:

scala> val start = LocalDateTime.of(2021, 1, 1, 0, 0)
val start: java.time.LocalDateTime = 2021-01-01T00:00
                                                                                                                                                                           
scala> val end = LocalDateTime.of(2021, 1, 1, 3, 30)
val end: java.time.LocalDateTime = 2021-01-01T03:30
                                                                                                                                                                           
scala> val interval = 1
val interval: Int = 1                                                                                                                                                                          
                                                                                                                                                                           
scala> val seq = Iterator.iterate(start)(_.plusHours(interval)).takeWhile(end.isAfter).toSeq
val seq: Seq[java.time.LocalDateTime] = List(2021-01-01T00:00, 2021-01-01T01:00, 2021-01-01T02:00, 2021-01-01T03:00)
  • Related