7

I want to create a list of dates with the values from startdate to enddate

This is something similar to How to create a range of dates in R but in Elixir.

Since the list can be huge or sometime infinite (i.e., no end date), I want to also know how to create a stream of dates.

Community
  • 1
  • 1
shankardevy
  • 4,290
  • 5
  • 32
  • 49
  • 2
    You can look into `Stream.iterate/2`. You would give it an initial value and a function that takes the current date and emits the next one. Then to get a 100 days you could call `Enum.take(date_stream, 100)` on it. The calendar module in Erlang or libraries like Timex and Calends can help with the date operations. – José Valim Jun 20 '15 at 07:51
  • There's some further discussion on exactly this question both [here](http://onor.io/2014/11/07/athena-code/) and [here](http://codereview.stackexchange.com/questions/69120/generating-all-valid-dates) for whatever it's worth. – Onorio Catenacci Jun 22 '15 at 12:49

1 Answers1

11
 start_date = Calendar.Date.from_erl!({2014,12,27})
 date_stream = Stream.iterate(start_date, &(Calendar.Date.next_day!(&1)))
 Enum.take(date_stream, 10) 

 #=>
[%Calendar.Date{day: 27, month: 12, year: 2014},
 %Calendar.Date{day: 28, month: 12, year: 2014},
 %Calendar.Date{day: 29, month: 12, year: 2014},
 %Calendar.Date{day: 30, month: 12, year: 2014},
 %Calendar.Date{day: 31, month: 12, year: 2014},
 %Calendar.Date{day: 1, month: 1, year: 2015},
 %Calendar.Date{day: 2, month: 1, year: 2015},
 %Calendar.Date{day: 3, month: 1, year: 2015},
 %Calendar.Date{day: 4, month: 1, year: 2015},
 %Calendar.Date{day: 5, month: 1, year: 2015}]

thanks José Valim for pointing at right direction.

shankardevy
  • 4,290
  • 5
  • 32
  • 49