简体   繁体   中英

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

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!

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(_))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM