如何创建流和日期列表

时间:2015-06-20 07:10:27

标签: elixir

我想创建一个日期列表,其值从startdate到enddate

这与How to create a range of dates in R类似,但在Elixir中。

由于列表可能很大或有时无限(即没有结束日期),我还想知道如何创建日期流。

1 个答案:

答案 0 :(得分:10)

 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}]

感谢JoséValim指向正确的方向。