1

I need a method which returns a List of DateTime objects splitted by e.g 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.

Blauharley
  • 4,186
  • 6
  • 28
  • 47
  • Possible duplicate of [how to get a list of dates between two dates in java](http://stackoverflow.com/questions/2689379/how-to-get-a-list-of-dates-between-two-dates-in-java) – Avihoo Mamka Jan 06 '17 at 11:37

1 Answers1

3

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
Kolmar
  • 14,086
  • 1
  • 22
  • 25