Date ranges in Elixir?

Does Elixir support date ranges? For example, could it be something like this Ruby code in Elixir?

require 'date'

d1 = Date::civil 2015, 1, 1
d2 = Date::civil 2015, 1, 7

(d1..d2).each {|d| puts d }

Output:

2015-01-01
2015-01-02
2015-01-03
2015-01-04
2015-01-05
2015-01-06
2015-01-07
+6
source share
4 answers

The @bitwalker suggestion is excellent. If you want to do this in your Elixir native code:

def generate_all_valid_dates_in_range(start_date, end_date) when start_date <= end_date do
  (:calendar.date_to_gregorian_days(start_date) .. :calendar.date_to_gregorian_days(end_date))
  |> Enum.to_list
  |> Enum.map (&(:calendar.gregorian_days_to_date(&1)))
end

Read more about this solution and how I developed it with the great help of the Elixir community on my blog . But Timex is the best solution in my estimation.

+4
source

Using Calendar , you can get a stream of dates after a specific date. Example:

alias Calendar.Date

d1 = Date.from_erl! {2015, 1, 1}
d2 = Date.from_erl! {2015, 1, 1}
Date.days_after_until(d1, d2)

, true . :

Date.days_after_until(d1, d2, true) |> Enum.to_list

[%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},
 %Calendar.Date{day: 6, month: 1, year: 2015},
 %Calendar.Date{day: 7, month: 1, year: 2015}
+4

timex_interval timex . , timex - , .

+3
source

Yes,

Using the Date Module

range = Date.range(~D[2001-01-01], ~D[2002-01-01])

Enum.each(range, fn(x) -> IO.puts x end)

exit

2001-01-01
2001-01-02
2001-01-03
2001-01-04
2001-01-05
2001-01-06
2001-01-07
2001-01-08
2001-01-09
2001-01-10

until the last day, i.e. 2002-01-01

0
source

Source: https://habr.com/ru/post/1611013/


All Articles