I need a method which returns a List of DateTime objects splitted by eg hour
Example
DateTime start = DateTime.now() //2017-01-01 11:00:00
DateTime end = DateTime.now().plusHours(10) //2017-01-01 21:00:00
Expected Result
List[2017-01-01 **11**:00:00,2017-01-01 **12**:00:00,2017-01-01**13**:00:00...
2017-01-01 **21**:00:00]
Right now i am using workaround that i am not happy with
while(start.isBefore(end)){
start = startVar.plusHours(1)
//do something with start
}
Please, share your ideas.
If you know how many elements in the List
you want, you can use List.iterate
:
List.iterate(DateTime.now(), 10)(_.plusHours(1))
But if you have a start and end dates, you can use Iterator.iterate
and then convert it to List
(or just process the values in the Iterator
directly):
val start = DateTime.now()
val end = DateTime.now().plusHours(10)
Iterator.iterate(start)(_.plusHours(1)).takeWhile(_.isBefore(end)).toList
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.